views:

108

answers:

3

Say this is my string

$string = 'product[0][1][0]';

How could I use that string alone to actually get the value from an array as if I had used this:

echo $array['product'][0][1][0]

I've messed around with preg_match_all with this regex (/\[([0-9]+)\]/), but I am unable to come up with something satisfactory.

Any ideas? Thanks in advance.

+3  A: 

You could use preg_split to get the individual array indices, then a loop to apply those indices one by one. Here's an example using a crude /[][]+/ regex to split the string up wherever it finds one or more square brackets.

(Read the [][] construct as [\]\[], i.e. a character class that matches right or left square brackets. The backslashes are optional.)

function getvalue($array, $string)
{
    $indices = preg_split('/[][]+/', $string, -1, PREG_SPLIT_NO_EMPTY);

    foreach ($indices as $index) 
        $array = $array[$index];

    return $array;
}
John Kugelman
A: 

This is prettttty hacky, but this will work. Don't know how much your array structure is going to change, either, this won't work if you get too dynamic.

$array = array();

$array['product'][0][1][0] = "lol";

$string = 'product[0][1][0]';

$firstBrace = strpos( $string, "[" );

$arrayExp = substr($string, $firstBrace );
$key = substr( $string, 0, $firstBrace );

echo $arrayExp, "<br>";
echo $key, "<br>";

$exec = "\$val = \$array['".$key."']".$arrayExp.";";

eval($exec);

echo $val;
Josh
A: 

What about using eval()?

<?php
  $product[0][1][0] = "test";
  eval ("\$string = \$product[0][1][0];");
  echo $string . "\n";
  die();
?>
merkuro