PHP dynamic array name with loop

356 views Asked by At

I need to get values of array through a loop with dynamic vars. I can't understand why the "echo" doesn’t display any result for "$TAB['b']". Do you know why ?

The test with error message : https://3v4l.org/Fp3GT

$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb"; 
$TAB['b']['c'] = "ccccc"; 


$TAB_paths = ["_a", "['b']", "['b']['c']"];

foreach ($TAB_paths as $key => $value) {
    echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
    }
4

There are 4 answers

2
Patrick Q On BEST ANSWER

You are treating the array access characters as if they are part of the variable name. They are not.

So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.

Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.

$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';

$TAB_paths = array('b', 'c');

foreach ($TAB_paths as $key => $value) {
    echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}

Output:

$TAB['b'] : bbbbbb

$TAB['c'] : cccccc

DEMO

1
l'L'l On

It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:

$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];

Result:

${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
1
jwbradley On

Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.

$TAB_paths = array_merge($TAB_a1, $TAB_a2);

1
mahmoud salem On

You can define the variable first

foreach ($TAB_all as $key => $value) {
   ${"TAB_all" . $key} = $value;   
}

Now Explore the result:

foreach ($TAB_all as $key => $value) {
        print_r(${"TAB_all" . $key});   
}