Why can't I echo the values in an array directly?
$list = array('Max', 'Alice', 'Brigitte');
echo($list); //This doesn't work
//But this does
foreach($list as $l){
echo($l . " ");
};
Why can't I echo the values in an array directly?
$list = array('Max', 'Alice', 'Brigitte');
echo($list); //This doesn't work
//But this does
foreach($list as $l){
echo($l . " ");
};
Let's see if I can explain this in a good way. Basically $list has a lot of more elements and things associated with it. When echoing $list it doesn't really know how to handle it. It has to do with how array data types work in PHP.
You may have noticed that
echo($list);
does produce some output:This is because
$list
is cast to a string in the context ofecho
. In fact, if you had warnings turned on, you would see afor that statement. The defined behavior of PHP when converting arrays to strings is that arrays are always converted to the string
"Array"
.If you want to print the contents of the array without looping over it, you will need to use one of the various PHP functions that converts an array to a string more effectively. For a simple array of strings like your
$list
, you can just useimplode
.But if you need to deal with a more complex array (if some elements are themselves arrays, for example) this will not work because of the same array to string conversion issue.
Because echo — Output one or more STRINGS
http://php.net/manual/en/function.echo.php
Try using var_dump for array http://php.net/manual/en/function.var-dump.php
or print_r http://php.net/manual/en/function.print-r.php