0
$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

$key = '[1][0]';
$str = '$cars'.$key;
echo $str."\n";
eval($str);

Output:

$cars[1][0]
PHP Parse error:  syntax error, unexpected end of file in ... : eval()'d code on line 1

I'm expecting it to print the value, i.e BMW

1 Answer 1

2

Let's start with the obvious "when is eval evil in php?", which I assume you know.

For your error there's multiple reasons. First of all, the code you're executing is the following (which you know as you're printing it):

$cars[0][1]

Just like this wouldn't do anything in raw PHP (<?php $foo; ?>) it also does nothing in the eval statement (I've added an echo in my code to fix this). Secondly, you're forgetting the semicolon at the end of the statement (as with any PHP).

The correct statement would therefore look like this:

<?php

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

$key = '[1][0]';
$str = 'echo $cars' .$key . ';'; // "echo $cars[0][1];"
echo $str."\n";
eval($str); // will echo "BMW"

DEMO

If you'd rather have the value returned into a variable, use return:

<?php

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

$key = '[1][0]';
$str = 'return $cars' .$key . ';'; // "return $cars[0][1];"
echo $str."\n";
$var = eval($str);
var_dump($var); //string(3) "BMW"

DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

To sum it up, eval evaluates statements, not expressions as OP's thinking.
@georg Absolutely. That's a great way of putting it.
Yes, indeed I was thinking it evaluated expressions. The example on the PHP manual is not clear.

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.