Printing arrays in PHP can be maddening if you don’t know the shortcuts! There is always the standard:
foreach ($array as $key => $value)
{
echo $key.' is key<br>';
echo $value.' is value<br>';
}
but if it’s not an array (and you have error checking on), you’ll get an error:
Warning: Invalid argument supplied for foreach() in /home/username/public_html/file.php on line x
And unfortunately, putting the ‘@’ in front of the ‘foreach’ only yields another error:
Parse error: syntax error, unexpected T_FOREACH in /home/username/public_html/file.php on line x
Of course, you could do a check to see if it *is* an array, but that’s more lines of code, and we want it quick.
Here’s a clever way to get what I call in my Dreamweaver snippets panel a “quick print of array”:
print '<pre>'; print_r($_POST); print '</pre>';
Here’s what it will look like:
Array
(
[asso_key_name_1] => value 1
[asso_key_name_2] => value 2
)
That’s great, but suppose you have several arrays on one page you want to print the results for, how can you keep them apart? Simple! Put the name of the array after the first <pre> tag, like this:
print '<pre>_POST '; print_r($_POST); print '</pre>';
The results will be like this:
_POST Array
(
[asso_key_name_1] => value 1
[asso_key_name_2] => value 2
)
You can use this quick printing of arrays to print POST vars, SESSION vars, recordsets, any kind of PHP array!