Skip to content

Instantly share code, notes, and snippets.

@SDKiller
Created September 22, 2014 16:45
Show Gist options
  • Save SDKiller/09049655bcfa95dcd172 to your computer and use it in GitHub Desktop.
Save SDKiller/09049655bcfa95dcd172 to your computer and use it in GitHub Desktop.
ArrayHelper
public static function getValue($array, $key, $default = null)
{
if ($key instanceof \Closure) {
return $key($array, $default);
}
if (is_array($array) && array_key_exists($key, $array)) {
return $array[$key];
}
if (($pos = strrpos($key, '.')) !== false) {
$array = static::getValue($array, substr($key, 0, $pos), $default);
$key = substr($key, $pos + 1);
}
if ($array instanceof \yii\base\Object) {
return ($array->canGetProperty($key, false) || array_key_exists($key, get_object_vars($array))) ? $array->key : $default;
} elseif (is_object($array)) {
return array_key_exists($key, get_object_vars($array)) ? $array->$key : $default;
} elseif (is_array($array)) {
return array_key_exists($key, $array) ? $array[$key] : $default;
} else {
return $default;
}
}
@SDKiller
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment