Created
March 3, 2014 19:36
-
-
Save Ider/9332947 to your computer and use it in GitHub Desktop.
Safe way to get index from array with default return value even if key dose not exist
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
/** | |
* Get value from $array with index or indics given by $keyOrKeys. | |
* @param array $array The array to get value from. | |
* @param mixed $keyOrKeys A single key, or a numeric array that contains multiple keys | |
* to fetch from multidimensional array. | |
* Key cound be either numeric or string. | |
* If emtpy array given, the original $array will be returned. | |
* @param mixed $default The default value to be returned if the array dose not contain | |
* given key or midway value is not array type. | |
* @return mixed The value that associated in $array. | |
*/ | |
function idx($array, $keyOrKeys, $default = null) { | |
if (!is_array($keyOrKeys)) { | |
$key = $keyOrKeys; | |
return isset($array[$key])? $array[$key] : $default; | |
} | |
$keys = $keyOrKeys; | |
$count = count($keys); | |
$i = 0; | |
while ($i < $count && is_array($array)) { | |
$key = $keys[$i]; | |
if (!isset($array[$key])) { | |
break; | |
} | |
$array = $array[$key]; | |
$i++; | |
} | |
if ($i == $count) { | |
return $array; | |
} | |
return $default; | |
} | |
/* | |
function idxTEST() { | |
$a = array(0,1,2,3,4, | |
'hello' => 'world', | |
'a' => array(0,1,2,3,4, | |
'welcome' => 'back' | |
), | |
); | |
echo '<pre>'; | |
// Test on single-index | |
var_dump(idx($a, 0)); // 0 | |
var_dump(idx($a, 7)); // null | |
var_dump(idx($a, 7, 7)); // 7 | |
var_dump(idx($a, 'hello')); // world | |
// Test on multi-index | |
var_dump(idx($a, array('a', 0))); // 0 | |
var_dump(idx($a, array('a', 7), 7)); // 7 | |
var_dump(idx($a, array('a', 'welcome'))); // back | |
echo '</pre>'; | |
} | |
idxTEST(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment