Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$$ array variable in PHP [duplicate]

Tags:

php

reference

I can use $$ variables to refer variable like this

$var = 'car';
$car = 'Lamborghini';
echo $$var;

Above code will echo Lamborghini.

However I am having a code like this:-

$var = "['acct_1']['etc']['anotherInfo']['sing']";
$var = 'arr'.$var;
echo $arr['acct_1']['etc']['anotherInfo']['sing'] ;
echo $$var;

First echo prints the correct value but $$var doesn't give the correct value.

Any help is much appreciated.

Thanks

like image 993
Jatin Dhoot Avatar asked Apr 27 '26 13:04

Jatin Dhoot


1 Answers

You can always keep the keys in an array, and then iterate on them to resolve the value correctly:

$keys = ['acct_1', 'etc', 'anotherInfo', 'sing'];

$val = $arr;
foreach($keys as $key) {
    $val = $val[$key];
}

Now, both $arr['acct_1']['etc']['anotherInfo']['sing'] and $val have the same value.

Try it in this demo.

Edit:

You already have the $keys array in $indexInfo. You should be able to use it like so:

function replaceValue($arr, $indexInfo, $char)
{
    // $indexInfo is all you need!
    $var = $arr;
    foreach($indexInfo as $key) {
        $var = $var[$key];
    }
    echo $arr['acct_1']['etc']['anotherInfo']['sing'] . "\n";
    echo $var  . "\n";
    die($var);
}
like image 131
nickb Avatar answered Apr 30 '26 05:04

nickb



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!