$$ array variable in PHP
I can use $$ variables to reference a variable like
$var = 'car';
$car = 'Lamborghini';
echo $$var;
Above the code will echo a Lamborghini .
However, I have a code like this: -
$var = "['acct_1']['etc']['anotherInfo']['sing']";
$var = 'arr'.$var;
echo $arr['acct_1']['etc']['anotherInfo']['sing'] ;
echo $$var;
The first echo outputs the correct value, but the $$ var does not give the correct value.
Any help is greatly appreciated.
thank
source to share
You can always store the keys in an array and then iterate over them to determine 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 this demo .
Edit:
You already have an array $keys
in $indexInfo
. You should be able to use it like this:
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);
}
source to share
This will not work unfortunately, however why not do something like this
/**
* Search into a multi dimensional array to find arbitrary data
* @param array $array The array to search
* @param string ... Any number of array keys
* @return mixed
*/
function deepArraySearch(array $array) {
$keys = func_get_args();
array_shift($keys); // First element is the array
// If no more keys to use
if(!$keys) {
return $array;
}
$nextKey = array_shift($keys);
$nextData = $array[$nextKey];
// Nothing left to search
if(!is_array($nextData )) {
return $nextData ;
}
array_unshift($keys, $nextData);
return call_user_func_array('deepArraySearch', $keys);
}
$arr = ['one' => ['two' => ['three' => 'data']]];
print_r(deepArraySearch($arr, 'one'));
print_r(deepArraySearch($arr, 'one', 'two'));
print_r(deepArraySearch($arr, 'one', 'two', 'three'));
echo PHP_EOL;
In your case, I am guessing it would work like
$arr = ['acct_1' => ['etc' => ['anotherInfo' => ['sing' => 'song']]]];
print_r(deepArraySearch($arr, 'acct_1', 'etc', 'anotherInfo', 'sing')); // song
Final note:
If you are using PHP 5.6, 7 or HHVM this function is more convenient:
<?php
/**
* Search into a multi dimensional array to find arbitrary data
* @param array $array The array to search
* @param string ... Any number of array keys
* @return mixed
*/
function deepArraySearch(array $array, ...$keys) {
// If no more keys to use
if(!$keys) {
return $array;
}
$nextKey = array_shift($keys);
$nextData = $array[$nextKey];
// Nothing left to search
if(!is_array($nextData )) {
return $nextData ;
}
return deepArraySearch($nextData, ...$keys);
}
Demo: http://3v4l.org/vmocO
source to share