Access an array variable, with its name stored as string in another array

Hi, please, can you look at my example?

I want to access an array.
The name of this array is stored as string inside another array.
I obtained the name of the array, and done the dump in a successful way as var_dump($$array["array_name"]); look.

But, There is an ERROR when I try to access a particular index as in var_dump($$array["array_name"][1]);.

I don’t know why! Can you help me? Thanks!

<?php
   $foo = array(0 => "string text",
                1 => "another line of string text",
                2 => "etc etc");

   $array = array("array_name" => "foo");

   $array_name = $array["array_name"];



   echo "<p>access directly the array with name 'foo', the row 1</p>";
   var_dump($foo[1]);

   echo "<br><p>access directly the array that contain array variables names</p>";
   var_dump($array["array_name"]);

   echo "<br><p>access indirectly the array that contain array variables names</p>";
   var_dump($$array["array_name"]);

   echo "<br><p>access indirectly the array that contain array variables names, row 1, ERROR!! WHY?</p>";
   var_dump($$array["array_name"][1]);

   echo "<br><p>access indirectly the array that contain array variables names, row 1, ERROR!! WHY?</p>";
   var_dump($$array_name[1]);

?>

Ambiguity. Note the curly braces. Though I’m not sure the last one is correct.

echo "<br><p>access indirectly the array that contain array variables names, row 1, ERROR!! WHY?</p>";
var_dump(${$array["array_name"]}[1]);
   
echo "<br><p>access indirectly the array that contain array variables names, row 1, ERROR!! WHY?</p>";
var_dump(${$array_name}[1]);

http://php.net/manual/en/language.variables.variable.php

2 Likes

If I am not mistaken, it appears to me that there is no index [1] in $array["array_name"], but rather it appears that $array stores one element at "array_name". Basically $array looks like this:
array=> ["array_name"] => "foo"
You are passing it a string "foo" and not the variable $foo.
Additionally, $array_name doesn’t appear to be an array, so you won’t be able to do var_dump($$array_name[1]); on it, instead it just stores the string "foo"

@droopsnoot has resolved the matter. Many thanks!

@fencerman2 $array_name is string that contains the name of the array variable.
So, we can consider $$array_name[1] as:
$$array_name[1]
=${$array_name}[1] =
=${foo}[1] =
= $foo[1]

so, If I understand, the reasoning in my first post was substantially right, but working with arrays produces ambiguity problem that someone can resolve following what droopsnoot said using the curly brackets.

Some of those ambiguity problems are resolved one way in PHP 5 and the opposite way in PHP 7 so you should always use {} to remove the ambiguity or the code may break in the future (who knows which way future versions will resolve those ambiguities).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.