#4: Printing the Contents of an Array

Let's say that you have been adding and subtracting items from an array, but you're running into some problems. What you really need is to view the contents of an array as they were at a specific line in your script. There's a really easy way to do this that doesn't get nearly the attention that it should from PHP tutorials around the world—the print_r() function! Here's an example:

<?php

$alacarte = array("chocolate ice cream",
                  "vanilla pudding",
                  "snozzberry whip");
$menu = array ("appetizer" => "fruit",
               "entree" => "roast beef",
               "dessert" => $alacarte);

print_r($menu);

?>

The print_r() function prints arrays onscreen in a format that humans can read. This is especially handy when you're dealing with multidimensional ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.