Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "Undefined variable" when trying to resolve a multi-dimensional array?

Tags:

php

I'm trying to retrieve an item from a multi-dimensional array through a string that describes the path into the array (like first.second.third).

I've chosen the approach as shown here (also available on ideone):

<?php
    // The path into the array
    $GET_VARIABLE = "a.b.c";
    // Some example data
    $GLOBALS["a"]= array("b"=>array("c"=>"foo"));

    // Construct an accessor into the array
    $variablePath = explode( ".", $GET_VARIABLE );
    $accessor = implode( "' ][ '", $variablePath );
    $variable = "\$GLOBALS[ '". $accessor . "' ]";

    // Print the value for debugging purposes (this works fine)
    echo $GLOBALS["a"]["b"]["c"] . "\n";
    // Try to evaluate the accessor (this will fail)
    echo $$variable;
?>

When I run the script, it will print two lines:

foo
PHP Notice:  Undefined variable: $GLOBALS[ 'a' ][ 'b' ][ 'c' ] in ...

So, why does this not evaluate properly?

like image 886
Oliver Salzburg Avatar asked Jul 18 '26 07:07

Oliver Salzburg


1 Answers

I think the $$ notation only accepts a variable name (ie. the name of a variable). You are actually trying to read a variable named "$GLOBALS[ 'a' ][ 'b' ][ 'c' ]", which does not exist.

As an alternative ($GET_VARIABLE seems to be your input string), you could try this:

$path = explode('.', $GET_VARIABLE);
echo $GLOBALS[$path[0]][$path[1]][path[2]];

Wrap this in a suitable loop to make it more dynamic; it seems to be trivial.

like image 130
RandomSeed Avatar answered Jul 20 '26 22:07

RandomSeed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!