Created
July 3, 2017 14:47
-
-
Save amcsi/a4056acaa383160c9448af1aff35250c 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 | |
| declare(strict_types=1); | |
| /** | |
| * Walks nested array structures to retrieve values. | |
| */ | |
| class ArrayWalkerReference | |
| { | |
| /** | |
| * Walks the specified nested array elements according to the ordered list | |
| * of keys specified by the path and returns the value of the matching | |
| * element. | |
| * | |
| * @param array $array Nested array elements. | |
| * @param array $path Path. | |
| * | |
| * @return mixed The matching element's value if found, otherwise null. | |
| */ | |
| public static function walk(array $array, array $path) | |
| { | |
| while (count($path)) { | |
| if (!is_array($array)) { | |
| return null; | |
| } | |
| $array = &$array[array_shift($path)]; | |
| } | |
| return $array; | |
| } | |
| } | |
| $array = ['a' => ['b' => ['c' => 'foo']]]; | |
| $path = ['a', 'b', 'c']; | |
| $times = 1000000; | |
| $start = microtime(true); | |
| for ($i = 0; $i < $times; ++$i) { | |
| ArrayWalkerReference::walk($array, $path); | |
| } | |
| printf("reference: %.4f\n", microtime(true) - $start); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment