Many times you need to print or echo an array value. Sometimes you may also need to view the entire contents of an array for debugging or other purposes. Let’s take a look at a few different ways of doing this.
Using PHP: Echo Array Values One by One
If we just need to print a particular value from an array, it’s fairly easy. You just need to append [#] to the end of the array name to get the element #. In case that’s not clear look at the following example:
<?php $my_array = array("stuff1", "stuff2", "stuff3"); echo $my_array[0] . "\n"; echo $my_array[1] . "\n"; echo $my_array[2] . "\n"; ?>
This outputs:
stuff1
stuff3
stuff2
The “. \n” just makes sure the output is on three separate lines instead of all crammed together on one.
Using PHP: Print Array Contents Inline
A common use of PHP is to print out the contents of an array element inline with text, such as in an HTML page. This is the same approach you would use to print a PHP variable inline but let’s look at an example:
Here is some sentence I am writing in one of my HTML pages. Did you know my site has <?php print $my_site_statistics['page_count'] ?> pages in it?
The output from this would be something like: Did you know my site has 431 pages in it?
Using PHP: View Array Contents
What if you want to see all the contents in an array. For example if you wanted to know what values were in the array. This can be done using print_r as in the following example:
<?php $my_array = array("stuff1", "stuff2", "stuff3"); print_r($my_array); ?>
The output is:
Array
(
[0] => stuff1
[1] => stuff2
[2] => stuff3
)
Sometimes when using print_r on an HTML page the formatting gets lost. To fix this simply wrap print_r in pre tags.













Written by admin
Topics: PHP Reference