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

eozzy
  • 66,048
  • 104
  • 272
  • 428

1 Answers1

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

Community
  • 1
  • 1
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102