Created
January 23, 2011 11:23
-
-
Save tomschlick/791999 to your computer and use it in GitHub Desktop.
This function allows you to dive into an array and provide a fallback value in case the element you want does not exist.
This file contains 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 | |
function array_element($array, $key, $default = false) | |
{ | |
$key = explode('.', $key); | |
if(count($key) > 1) | |
{ | |
if ( ! is_array($array) || ! array_key_exists($key[0], $array)) | |
{ | |
return $default; | |
} | |
$array = $array[$key[0]]; | |
unset($key[0]); | |
$key = implode('.', $key); | |
$array = array_element($array, $key, $default); | |
return $array; | |
} | |
else | |
{ | |
$key = $key[0]; | |
if ( ! is_array($array) || ! array_key_exists($key, $array)) | |
{ | |
return $default; | |
} | |
return $array[$key]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment