Created
July 3, 2017 14:48
-
-
Save amcsi/63de44f8baba1d3c178ead69ac2c9930 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 ArrayWalkerValue | |
{ | |
/** | |
* 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) { | |
ArrayWalkerValue::walk($array, $path); | |
} | |
printf("value: %.4f\n", microtime(true) - $start); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment