Skip to content

Instantly share code, notes, and snippets.

@ponich
Created May 23, 2018 14:37
Show Gist options
  • Select an option

  • Save ponich/afff1b3860fd5ea58ca26fb0e1e90d5b to your computer and use it in GitHub Desktop.

Select an option

Save ponich/afff1b3860fd5ea58ca26fb0e1e90d5b to your computer and use it in GitHub Desktop.
Native helpers
<?php
if (!function_exists('array_get')) {
/**
* Get value from array by key
*
* @param array $array
* @param string $key
* @param mixed $default
* @return mixed
* @example
* $array = [
* 'contact' => ['Name' => 'Alex']
* ];
*
* echo array_get($array, 'contact.name'); // Alex
* echo array_get($array, 'contact.fullname', 'Anonymous'); // Anonymous
*/
function array_get($array, $key, $default = null)
{
if (!is_array($array)) {
return $default;
}
if (is_null($key)) {
return $array;
}
if (isset($array[$key])) {
return $array[$key];
}
if (strpos($key, '.') === false) {
return $default;
}
$segments = explode('.', $key);
$searchKey = null;
foreach ($segments as $i => $segment) {
if ($i == 0) {
$searchKey = $segment;
} else {
$searchKey = $searchKey . '.' . $segment;
}
if (isset($array[$segment])) {
if ($searchKey == $key) {
return $array[$segment];
}
$newKey = str_replace($searchKey . '.', '', $key);
return array_get($array[$segment], $newKey, $default);
}
}
return $array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment