Created
September 5, 2016 20:50
-
-
Save m3g4p0p/8175830059cded5f03f6b33840ed7e32 to your computer and use it in GitHub Desktop.
Access a specific element of a nested array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Return the reference to an element/subarray | |
* of an array, specified by a key array | |
* | |
* @param array &$array Array to access by reference | |
* @param mixed $keys Array of the keys | |
* @return mixed Reference to the match | |
*/ | |
function &array_access(&$array, $keys) { | |
// If there are keys left to walk down | |
// a nested array | |
if ($keys) { | |
$key = array_shift($keys); | |
// Get and return the reference to the | |
// subarray with the current key | |
$sub = &array_access( | |
$array[$key], | |
$keys | |
); | |
return $sub; | |
} else { | |
// Return the match | |
return $array; | |
} | |
} | |
// Usage | |
$array = []; | |
$keys =['houses', 'ocean_view', 'state']; | |
// Here we're accessing the array match | |
// by reference | |
$reference = &array_access($array, $keys); | |
$reference = 'Oregon'; | |
// But we might also just return the value | |
$value = array_access($array, $keys); | |
echo $value; | |
$value = 'Ibiza'; | |
print_r($array); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment