Skip to content

Instantly share code, notes, and snippets.

@jelmervdl
Created October 17, 2017 10:16
Show Gist options
  • Save jelmervdl/a461bfe445402542b2a5b736f1ce8163 to your computer and use it in GitHub Desktop.
Save jelmervdl/a461bfe445402542b2a5b736f1ce8163 to your computer and use it in GitHub Desktop.
Traverse a nested PHP array/object structure using a path
<?php
function array_path($array, $path, $default_value = null)
{
// Construct the path
if (!preg_match('/^(?P<head>\w+)(?P<rest>(\[\w+\]|->\w+)*)$/', $path, $match))
throw new InvalidArgumentException("The path '$path' is malformed");
$steps = [['index' => $match['head']]];
if (!empty($match['rest'])) {
if (!preg_match_all('/\[(?P<index>\w+)\]|->(?P<property>\w+)/', $match['rest'], $match, PREG_SET_ORDER))
throw new InvalidArgumentException('The rest of the path is malformed');
$steps = array_merge($steps, $match);
}
// Unwind the path
foreach ($steps as $step) {
if (isset($step['property'])) {
if (!isset($array->{$step['property']}))
return $default_value;
else
$array = $array->{$step['property']};
} else {
if (!isset($array[$step['index']]))
return $default_value;
else
$array = $array[$step['index']];
}
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment