Skip to content

Instantly share code, notes, and snippets.

@selvinortiz selvinortiz/getValueByKey.php Secret
Created Dec 6, 2014

Embed
What would you like to do?
<?php
// @input
$key = isset($argv[1]) ? $argv[1] : 'name';
$data = array(
'name' => 'Brad Bell',
'mood' => 'Angry',
'family' => array(
'spouse' => array(
'name' => 'Brandon Kelly'
),
'brother' => array(
'name' => 'That European Guy'
)
)
);
$default = isset($argv[2]) ? $argv[2] : '';
// @usage
echo print_r(getValueByKey($key, $data, $default), true)."\n";
// @process
function getValueByKey($key, array $data, $default = null)
{
// @assert $key is a non-empty string
// @assert $data is a loopable array
// @otherwise return $default value
if (!is_string($key) || empty($key) || !count($data))
{
return $default;
}
// @assert $key contains a dot notated string
if (strpos($key, '.') !== false)
{
$keys = explode('.', $key);
foreach ($keys as $innerKey)
{
// @assert $data[$innerKey] is available to continue
// @otherwise return $default value
if (!array_key_exists($innerKey, $data))
{
return $default;
}
$data = $data[$innerKey];
}
return $data;
}
// @fallback returning value of $key in $data or $default value
return array_key_exists($key, $data) ? $data[$key] : $default;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.