Skip to content

Instantly share code, notes, and snippets.

@amcsi
Created July 3, 2017 14:48
Show Gist options
  • Save amcsi/63de44f8baba1d3c178ead69ac2c9930 to your computer and use it in GitHub Desktop.
Save amcsi/63de44f8baba1d3c178ead69ac2c9930 to your computer and use it in GitHub Desktop.
<?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