I have array $arr=array("a"=>array("b"=>123))
and I need to do with it something like this:
$a='[a][b]';
echo $arr{$a};
but it doesnt work;
echo $arr[a][b]; – works fine, but it’s not what I need. =(
PHP manual says:
if you write $$a1 then the parser needs to know if you meant to use $a1 as a variable, or if you wanted $$a as the variable and then the 1 index from that variable. The syntax for resolving this ambiguity is: ${$a1} for the first case and ${$a}1 for the second. >> php manual
but “echo ${$a};” and “echo $arr{$a};” and all the other variations output nothing.
UPDATE
in short, I need to delete an element of assotiative array via form.
For example, I have $a=array(‘abc’=>’def’);
and html form
<form><input name="deleteIT" value="[abc]"></form>
So, after submitting I want to delete from $a variable $deleteIT value.
Is this close enough to what you need?
Addendum: The answer above will work if the array
$arralways has exactly two levels. If it might have more (or less), something like the following could work:The function above takes two arrays as arguments: one containing the value we want, and another listing the keys we need to locate it in the first array. For example, if we have an array like this:
then
would print
123.Converting string keys into an array suitable for the second argument to
array_get_nested()depends on how the keys are formatted, but it could be as simple as callingexplode()with a suitable delimiter. For example, the last line of code above could be rewritten as:To modify nested arrays, we can use a similar function:
Note that PHP conveniently “autovivifies” arrays for us, so we can, for example, take a previously undefined variable
$fooand turn it into a three-level nested array simply with: