Last active
May 29, 2024 15:46
-
-
Save christopherarter/4f78aed192890d956161bc7334038f4c to your computer and use it in GitHub Desktop.
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 | |
| /** | |
| * Get an item from an array using "dot" notation. | |
| * Provides a safe way to access nested array values, | |
| * and also return a default value if the key does not exist. | |
| * | |
| * @param array $data | |
| * @param string|int $key | |
| * @param mixed $default | |
| * @return mixed | |
| */ | |
| function data_get($data, $key, $default = null) { | |
| if (is_null($key)) { | |
| return $data; | |
| } | |
| if (is_array($key)) { | |
| $return = []; | |
| foreach ($key as $k) { | |
| $return[$k] = data_get($data, $k, $default); | |
| } | |
| return $return; | |
| } | |
| foreach (explode('.', $key) as $segment) { | |
| if (!is_array($data) || !array_key_exists($segment, $data)) { | |
| return $default; | |
| } | |
| $data = $data[$segment]; | |
| } | |
| return $data; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment