How to Echo an Array in PHP




If you’re just starting PHP, it may not be immediately obvious how to print the contents of an array, but rest assured there are several very simple methods for displaying the contents of an array.

We’ll go through simple methods such as print_r($array) and var_dump($array) but also show some other more unique methods.

The Array

To start with let’s define a fairly complex array for testing purposes – this will show us what each function will output in most situations! As you can see, it contains numeric keys, string keys, no keys defined, nested arrays, a stdClass object AND a DateTime object!

<?php
$object = new stdClass();
$object->variable = "value";
$object->foo = "bar";
$date = new DateTime();
$array = array(
1,
"stringElement",
"stringKey" => 1,
"boolean" => True,
array(
1,
"2",
"3" => "four",
),
"subArray" => array(
1,
"2",
"3" => "four",
"five" => "six",
"triplyNested" => array(
1,
"2",
"three" => "four"
),
),
"someObject" => $object,
"DateTime object" => $date
);
?>

So how are we going to deal with this monstrosity?? Let’s have a look at each method:

print_r

The PHP print_r function is a go-to workhorse function for displaying about any variable.

Lets see what we get using  print_r

print_r($array);
/* Output
Array
(
[0] => 1
[1] => stringElement
[stringKey] => 1
[boolean] => 1
[2] => Array
(
[0] => 1
[1] => 2
[3] => four
)
[subArray] => Array
(
[0] => 1
[1] => 2
[3] => four
[five] => six
[triplyNested] => Array
(
[0] => 1
[1] => 2
[three] => four
)
)
[someObject] => stdClass Object
(
[variable] => value
[foo] => bar
)
[DateTime object] => DateTime Object
(
[date] => 2015-01-13 22:45:41
[timezone_type] => 3
[timezone] => Europe/London
)
)
*/

Nice and easy to read! But what if we want to know the types of variables? That’s why we have…

var_dump

The PHP built in function var_dump is another workhorse for displaying variables and displays the types of the variables along with it – this can sometimes be very helpful if you’re not quite sure whether variables are coming as string, numbers, booleans, etc.

So, what do we get with var_dump ?

var_dump($array);
/* Output
array(8) {
[0]=>
int(1)
[1]=>
string(13) "stringElement"
["stringKey"]=>
int(1)
["boolean"]=>
bool(true)
[2]=>
array(3) {
[0]=>
int(1)
[1]=>
string(1) "2"
[3]=>
string(4) "four"
}
["subArray"]=>
array(5) {
[0]=>
int(1)
[1]=>
string(1) "2"
[3]=>
string(4) "four"
["five"]=>
string(3) "six"
["triplyNested"]=>
array(3) {
[0]=>
int(1)
[1]=>
string(1) "2"
["three"]=>
string(4) "four"
}
}
["someObject"]=>
object(stdClass)#1 (2) {
["variable"]=>
string(5) "value"
["foo"]=>
string(3) "bar"
}
["DateTime object"]=>
object(DateTime)#2 (3) {
["date"]=>
string(19) "2015-01-13 22:47:48"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/London"
}
}
*/

Nice, but a bit harder to read sometimes!

foreach loop

We can always just loop over the array. This works for those cases when we have very simple arrays, but fails for more complex ones:

foreach($array as $key => $var){
echo $key, " => ", $var, "\n";
}
/* Output
0 => 1
1 => stringElement
stringKey => 1
boolean => 1
2 => 
Notice:  Array to string conversion in C:\test.php on line 3
Array
subArray => 
Notice:  Array to string conversion in C:\test.php on line 3
Array
someObject => 
Catchable fatal error:  Object of class stdClass could not be converted to string in C:\test.php on line 3
*/

This falls over when nested arrays and objects start to appear, unfortunately! It didn’t even make it to the DateTime object because of the fatal error on the stdClass object.

Recursive Function

The last method employs (quite a complex!) recursive function that loops over each element of an array or object and echos it – harder than it sounds! Here’s the function:

<?php
/**
* Recursively iterates over $var, displaying each
* property/variable contained within
* @param  mixed   $var          Variable of any type
* @param  boolean $displayTypes Whether to display the types along with values
* @param  integer $depth        private var for telling how deep we are
* @return null                  always returns null
*/
function display($var, $displayTypes = True, $depth = 0){
$add = '';
if($displayTypes){
if(is_object($var)){
echo 'Object: ' . get_class($var);
} else {
echo sprintf('%-7s',gettype($var));
}
$add = '    ';
}
if(isIterable($var)){
if($depth>0 || $displayTypes) echo "\n";
if($displayTypes){
echo $add.str_repeat('    ', $depth)."(\n";
}
foreach($var as $key => $val){
echo str_repeat('    ', $depth);
if($displayTypes){
echo str_repeat($add, 2);
echo sprintf('%-7s',gettype($key));
echo ' ';
}
if(is_string($key)){
echo '["'.$key.'"]';
} else {
echo '['.$key.']';
}
echo " => ";
display($val, $displayTypes, $depth+1);
}
if($displayTypes){
echo "".$add.str_repeat('    ', $depth).")\n";
}
} else {
if($displayTypes){
echo ' ';
}
if(is_string($var)){
echo '"'.$var . "\"\n";
} else {
echo $var . "\n";
}
}
return null;
}
/**
* Determines if a variable is iterable or not
* @param  mixed   $var The input variable...
* @return boolean      Whether we can iterate over it or not
*/
function isIterable($var) {
set_error_handler(function ($errno, $errstr, $errfile, $errline, array $errcontext)
{
throw new \ErrorException($errstr, null, $errno, $errfile, $errline);
});
try {
foreach ($var as $v) {
break;
}
} catch (\ErrorException $e) {
restore_error_handler();
return false;
}
restore_error_handler();
return true;
}
?>

and here’s the different outputs, depending on whether displayTypes is enabled or not:

<?php
display($array, False);
/* Output (without types)
[0] => 1
[1] => "stringElement"
["stringKey"] => 1
["boolean"] => 1
[2] => 
[0] => 1
[1] => "2"
[3] => "four"
["subArray"] => 
[0] => 1
[1] => "2"
[3] => "four"
["five"] => "six"
["triplyNested"] => 
[0] => 1
[1] => "2"
["three"] => "four"
["someObject"] => 
["variable"] => "value"
["foo"] => "bar"
["DateTime object"] => 
["date"] => "2015-01-13 22:53:38"
["timezone_type"] => 3
["timezone"] => "Europe/London"
*/
display($array);
/* Output (with types)
array  
(
integer [0] => integer 1
integer [1] => string  "stringElement"
string  ["stringKey"] => integer 1
string  ["boolean"] => boolean 1
integer [2] => array  
(
integer [0] => integer 1
integer [1] => string  "2"
integer [3] => string  "four"
)
string  ["subArray"] => array  
(
integer [0] => integer 1
integer [1] => string  "2"
integer [3] => string  "four"
string  ["five"] => string  "six"
string  ["triplyNested"] => array  
(
integer [0] => integer 1
integer [1] => string  "2"
string  ["three"] => string  "four"
)
)
string  ["someObject"] => Object: stdClass
(
string  ["variable"] => string  "value"
string  ["foo"] => string  "bar"
)
string  ["DateTime object"] => Object: DateTime
(
string  ["date"] => string  "2015-01-13 22:53:38"
string  ["timezone_type"] => integer 3
string  ["timezone"] => string  "Europe/London"
)
)
*/
?>

Nice! It seems to work fine, and the output is pretty, and customisable!

Note that some keys, that we defined with string values of integers (“3”, “4”) get turned into integers by PHP. This is highlighted by both var_dump and our display function – how odd!

Conclusion

There are several ways of printing an array in PHP, which one you use is up to you, depending on your needs. What we’ve learnt is that it’s actually harder to reliably display the contents of a variable, especially an array, than first thought!

You can get a copy of the display function on GitHub gists.

Leave a Reply