Changing values in a multi-dimensional array via reference (in PHP)? -
the following php function finds node in multi-dimensional array matching key:
<?php function & findbykey($array, $key) { foreach ($array $k => $v) { if(strcasecmp($k, $key) === 0) { return $array[$k]; } elseif(is_array($v) && ($find = findbykey($array[$k], $key))) { return $find; } } return null; } $array = [ 'key1' => [ 'key2' => [ 'key3' => [ 'key5' => 1 ], 'key4' => '2' ] ] ]; $result = findbykey($array, 'key3'); i want function return reference node if change $result original $array changes (like javascript objects).
<?php array_splice($result, 0, 0, '2'); //changes $array since `$result` reference to: $array['key1']['key2']['key3'] how can this?
you need 2 things:
1) specify $array parameter reference:
function & findbykey(&$array, $key) { 2) assign variable $result reference using &:
$result = &findbykey($array, 'key3'); since calling function recursively, need assign $find reference well.
altogether:
function & findbykey(&$array, $key) { foreach ($array $k => $v) { if(strcasecmp($k, $key) === 0) { return $array[$k]; } elseif(is_array($v) && ($find = &findbykey($array[$k], $key))) { return $find; } } return null; } $result = &findbykey($array, 'key3'); $result = 'changed'; print_r($array); wiki
Comments
Post a Comment