Mixed-mode processing

A key concept in PHP is that you can toggle PHP parsing mode whenever you want and as often as you want, and you can even do it inside a code block. Here is a basic PHP script:

<?php
    
if ($foo == $bar) {
        print
"Lots of stuff here";
        print
"Lots of stuff here";
        print
"Lots of stuff here";
        ...[
snip]...
        print
"Lots of stuff here";
        print
"Lots of stuff here";
    }
?>

As you can see, there are a lot of print statements that will only be executed if the variable $foo is the same as variable $bar. All the output is encapsulated into print statements, but PHP allows you to exit the PHP code island while still keeping the if statement code block open - here's how that looks.

<?php
    
if ($foo == $bar) {
?>
    Lots of stuff here
    Lots of stuff here
    Lots of stuff here
    ...[snip]...
    Lots of stuff here
    Lots of stuff here
<?php
    
}
?>

The "Lots of stuff here" lines are still only sent to output if $foo is equal to $bar, but we exit PHP mode to print it out. We then re-enter PHP mode to close the if statement, and continue - it makes the whole script easier to read.

 

Next chapter: Including other files >>

Previous chapter: Loops within loops

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar