The getValueByKey function used at https://selv.in/blog/traversing-arrays-with-dot-notation
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 | |
// @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