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

// returns null
var_dump($arr);

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

1
  • 1
    Why are you evaling that string? There has to be a better way to do this, such as json_decode or unserialize. Commented Oct 19, 2012 at 14:27

4 Answers 4

20

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');");
Sign up to request clarification or add additional context in comments.

4 Comments

got it, thanks. I didn't pay much attention to the Return Value, just looked at the example which doesn't use a return.
@user1643156: Why are you using eval in the first place? It's slow and insecure. There is probably a better way to do what you want.
@gen_Eric I don't know about user16... but I've got two variables and a selector in between. So 'return $rule["value"]' . $selector . '$target;' will give me true==true but that can change depending on the variables. Is there a better way for this case?
I don't know if it's the best way, but I might do switch($selector){}, instead of using eval(). Then something like case '==': $ret = $rule['value'] == $target;.
1

Did you mean

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

var_dump($arr);

1 Comment

You need to escape the $. You are in double quotes, so PHP is trying to interpolate $arr, since it doesn't exist you wind up evaling " = array('foo'=>'bar');".
0

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');");

Comments

0

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

1 Comment

thanks, I'm aware of the evil part of eval(). the function is only used by me (admin).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.