Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Dynamically accessing an associative array

EDITED FROM ORIGINAL THAT HAD IMPLIED ONLY 1 ACCESS

If I have an array that contains x number of arrays, each of the form

array('country' => array('city' => array('postcode' => value)))

and another array that might be

array('country', 'city', 'postcode') or array('country', 'city') 

depending on what I need to retrieve, how do I use the second array to identify the index levels into the first array and then access it.

like image 573
Jeff Greenberg Avatar asked Nov 26 '25 17:11

Jeff Greenberg


1 Answers

By nesting references with $cur = &$cur[$v]; you can read and modify the original value:
Live example on ide1: http://ideone.com/xtmrr8

$array = array('x' => array('y' => array('z' => 20)));
$keys = array('x', 'y', 'z');

// Start nesting new keys
$cur = &$array;
foreach($keys as $v){
    $cur = &$cur[$v];
}

echo $cur;  // prints 20
$cur = 30;  // modify $array['x']['y']['z']
like image 58
dynamic Avatar answered Nov 29 '25 10:11

dynamic



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!