Cannot echo the values in an array in Php [duplica

2020-05-07 03:49发布

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 . " ");
    };

标签: php
3条回答
Ridiculous、
2楼-- · 2020-05-07 04:07

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.

查看更多
可以哭但决不认输i
3楼-- · 2020-05-07 04:11

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.

查看更多
地球回转人心会变
4楼-- · 2020-05-07 04:17
登录 后发表回答