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