0

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 . " ");
    };
Shady
  • 74
  • 1
  • 8
  • The exact answer in the main reference question can be found at https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/24507107#24507107 – user31782 Dec 28 '19 at 11:56

3 Answers3

3

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

kosta
  • 615
  • 6
  • 11
  • You can also make it a string by gluing all elements together, `echo implode(", ", $list);`. Or access the values directly using the associated index, like `$list[1]` outputs "Alice" (because PHP starts on 0). – Qirel Jul 05 '16 at 22:34
0

You may have noticed that echo($list); does produce some output:

Array

This is because $list is cast to a string in the context of echo. In fact, if you had warnings turned on, you would see a

Notice: Array to string conversion

for 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 use implode.

echo implode(', ', $list);

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.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
-1

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.

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179