Skip to content

Instantly share code, notes, and snippets.

@tomschlick
Created January 23, 2011 11:23
Show Gist options
  • Save tomschlick/791999 to your computer and use it in GitHub Desktop.
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.
<?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