PHP eval(array_as_string) returns null

2020-03-27 05:58发布

$arr = eval("array('foo'=>'bar');");

// returns null
var_dump($arr);

Can someone please explain why did I get null instead of an array?

标签: php eval
4条回答
劫难
2楼-- · 2020-03-27 06:32

Did you mean

eval("\$arr = array('foo'=>'bar');"); 

var_dump($arr);
查看更多
劳资没心,怎么记你
3楼-- · 2020-03-27 06:36

You need to return the array.

From the docs:

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned.

So you need to do:

$arr = eval("return array('foo'=>'bar');");
查看更多
淡お忘
4楼-- · 2020-03-27 06:47

The eval function executes the php code given to it. As your code returns nothing, it gives null. You need to return the array and store it in a variable like,

$arr = eval("return array('foo'=>'bar');");
查看更多
【Aperson】
5楼-- · 2020-03-27 06:47

First of all, eval is highly discouraged as explained in the manual.

Also, you should be doing something like $arr = eval("return array('foo'=>'bar');"); ie. initialising $arr with the eval function. See it in action here

查看更多
登录 后发表回答