Created
May 23, 2018 14:37
-
-
Save ponich/afff1b3860fd5ea58ca26fb0e1e90d5b to your computer and use it in GitHub Desktop.
Native helpers
This file contains hidden or 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 | |
| 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