ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP Foundations

Embedding PHP in HTML

05/03/2001

Also in PHP Foundations:

Using MySQL from PHP, Part 2

Using MySQL from PHP

MySQL Crash Course, Part 3

MySQL Crash Course, Part 2

MySQL Crash Course

Today we will discuss how to use special syntax to apply conditionals and loops.

Embedding PHP in regular HTML

If you have been paying attention to our earlier articles, you hopefully have picked up on how PHP can be embedded into a regular HTML document. For example, we should already know that the following is an example of how PHP is embedded:

<html>
<head>
<title>My first PHP Page</title>
</head>
<body>
This is normal HTML code
<?php 
	
		// php code goes here
?>

Back into normal HTML

</body>
</html>

Further, we also learned how we could quickly output variables from PHP code without all of the hassle of an echo statement by doing the following:

<?=$variable?>

Today, we will extend our knowledge of embedded PHP by discussing how PHP can be used to control the flow of a web page through conditionals or repetition-control structures.

How it works

As mentioned in earlier articles, PHP will only process things that are enclosed within one of its valid code blocks (such as <?php and ?>). Because of this, PHP effectively ignores everything that it was not specifically told to process and can be used to our advantage. For example, what will the output from the following be?

<?php

    $var = 5;
  ?>

    $var = 10;<br />

The variable $var has a value of: 

<?=$var?><br />

Is this a valid script? Yes, the output would be the following:

    $var = 10;
    The variable $var has a value of: 5

Notice that with the second assignment of $var, when we attempt to change the value from 5 to 10, it has no effect because it is not enclosed within valid PHP code-block syntax. So, instead of being processed, it is simply displayed to the web browser.

Embedded conditionals

What if we wanted to display HTML only under specific conditions? For example, we only want PHP to display a navigation menu if the user is validated -- how could we do this? Using what we already know, we could simply put all the code for the HTML menu within echo statements (paying careful attention to add a backslash any time we need to output a quote for our HTML to the web browser) but this method can quickly become cumbersome and difficult to follow. Instead, to deal with situations like this, we will introduce a new flavor of our code-block syntax:

<?php if(conditions) { ?>
... HTML CODE ...
<?php } ?>

Although this may be confusing, remember how PHP will process this code. To start, it will evaluate the first line of a normal if statement and then begin a code block. Then, we turn off PHP parser and jump into normal HTML code (all of which PHP will simply output to the browser and ignore) until, finally, we return to PHP code and close our if statement. The result of this technique is a way for us to control regular and standard HTML with nearly no intrusion by PHP into the syntax. Although the above example works, a special syntax is provided for instances where PHP is being used simply to control the output of standard HTML code:

<?php if(conditions): ?>
... HTML CODE ...
<?php endif; ?>

This syntax is identical in function to the original example provided.

Other valid embedded syntax

Beyond simple if statements, most control structures provide an alternative syntax that allows us to embed PHP code within standard HTML quickly and easily. For example, below are definitions for our repetition statements while and for (starting with while):

<?php while(conditions) : ?>
... HTML CODE ...
<?php endwhile; ?>

And an identical syntax for an embedded for loop:

<?php for(init;conditions;increment) : ?>
... HTML CODE ...
<?php endfor; ?>

Embedded code in action

Now that we have a feel of the syntax behind embedded control structures, let's look at a likely situation where our new knowledge could be put to use. What if we wanted to list, in an HTML table, all the numbers between 1 and 7 and determine under what circumstances our friend Billy could purchase a candy bar? Before we begin, we should get an idea of exactly how our HTML table should be constructed. For our purposes, we will be creating a table of the following form:

1234567
nonononoyesyesyes

Now, let's take a loop at the HTML behind this table:

<html>
<body>
<table>
<tr>
  <td align="center">1</td>
  <td align="center">2</td>
  <td align="center">3</td>
  <td align="center">4</td>
  <td align="center">5</td>
  <td align="center">6</td>
  <td align="center">7</td>
</tr>
<tr>
  <td align="center">no</td>
  <td align="center">no</td>
  <td align="center">no</td>
  <td align="center">no</td>
  <td align="center">no</td>
  <td align="center">yes</td>
  <td align="center">yes</td>
  <td align="center">yes</td>
</tr>
</table>
</body>
</html>

Notice that, when dealing with static HTML we have no flexibility whatsoever to alter the content of the table without manually changing it. What if we wanted to show a table of all the possibilities from 1 to 100? Again, accomplishing such a task by hand is a waste of time. However, with PHP, we can find a solution to our dilemma quickly and easily:

<html>
<body>
<table>
<tr>
<?php for($l = 1; $l <=7; $l++) : ?>
<td align="center"><?=$l?></td>
<?php endfor; ?>
        </tr>
        <tr>
            <?php for($l = 1; $l <=7; $l++) : ?>
            <td align="center">
<?php if($l >= 5)  { 
        
        echo "yes";
    
    } else {

        echo "no";

    }
?>
</td>
<?php endfor; ?>
        </tr>    
</table>
</body>
</html>

What have we done? Looking at this example, we start by simply outputting the basic HTML code to construct the web page and begin a table. Then, we use PHP to start a for loop to count from 1 to 7. Within this loop, we display the HTML code to first start a table cell, then display the variable we are counting with ($L) and finally the HTML to close the table cell.

Once this has been completed, we close our row and start a new row and repeat the same looping process. This time, however, instead of simply outputting the looped variable, we use a conditional statement to determine if it is greater than or equal to the value 5 in which case we output "yes" or "no" depending on the value of $L. Finally, we finish the HTML for our table and web page and the script ends.

The result? Exactly the same static HTML page as we originally constructed except now we have the flexibility to examine any range with no extra effort. It is recommended that you play around and get very familiar with this syntax because it will be used quite often in future articles and in everyday practice.

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.