A trick I learned after a while coding PHP is that I can delay echoing output.
Just because your PHP script gets things in a particular order does not mean you need to send them for display in the browser in that same order.
It is very simple to achieve this by continuously adding the output to a variable.
Here is a little example - lets say you select names from an address book application and you want to display them in a HTML table.
(I have left out the database connectivity stuff)
Code: Select all
<?
// start the variable
$table = '<table>' . PHP_EOL ;
// loop thru database result set - as you do
foreach( $rows as $row ){
// here you concatenate strings to the variable $table
$table .= '<tr><td>' . $row['name'] . '</td></tr>' . PHP_EOL
}
// finally finish off the table
$table . = '</table>' . PHP_EOL
?>
Now you get on and do the other stuff you normally do, then at the appropriate moment you do something like this:
Code: Select all
<?
include $header ;
echo $table ;
include $footer ;
?>
Theres a few things about this example that I will explain:
When you concatenate a string you could do this - but it is long winded:
Code: Select all
$table = $table . '<tr><td>' . $row['name'] . '</td></tr>' . PHP_EOL ;
And the shortcut is to use .=
[gotcha1] Note there is no space between the . and the =
Code: Select all
$table .= '<tr><td>' . $row['name'] . '</td></tr>' . PHP_EOL ;
[gotcha2] Watch out for concatenating integers, the operator is not the same.
Code: Select all
$a= 7;
echo $a .= 6 ; // gives 76 (treats them as 2 strings)
echo $a += 4; // gives 80
The other thing you might be wondering about is the use of the constant PHP_EOL which means "PHP End Of Line", and causes the Operating System to insert it's end of line characters. So your code becomes more portable.
It is the equivalent of echo "\n" ; or echo "\r\n" ; etc. which I always found error_prone and ugly.
This is important if you value easy to read source code for your html as each PHP_EOL will cause a new line to appear.
When sending output to the browser, straight after sending the header info, it is important to send the main thing first (the H1 heading, the main story) but the page's supporting html, like menus and navigation is somewhat secondary.
The order in which you display it on the page may well be very different. Visually the navigation and menus may appear first or most prominently.
Well the same thing is true of your PHP, just because you assemble your navigation elements and breadcrumbs first, does not mean you have to send them to the browser first.
Recognising I could delay output was a small but important step on the road to separating concerns and responsibilities in my code, and in turn helped me evolve from a "PHP/html scripter" to a "PHP programmer".
I hope this helps you.