Skip to content

Instantly share code, notes, and snippets.

@crtl
Last active July 5, 2019 08:17
Show Gist options
  • Save crtl/62de35d8c891bf218affa9b8212a9361 to your computer and use it in GitHub Desktop.
Save crtl/62de35d8c891bf218affa9b8212a9361 to your computer and use it in GitHub Desktop.
Function to access associative arrays by string paths
/**
* @param string $path The path of keys to access
* @param array $array The array to read from
* @param string $seperator The seperator to split the string by
* @return array|mixed|null The requested value or null
*/
function array_path(string $path, array $array, string $seperator = ".") {
$parts = explode($seperator, $path);
$current = $array;
foreach ($parts as $part) {
if (!isset($current[$part])) {
return null;
}
$current = $current[$part];
}
return $current;
}
$data = [
"customers" => [
[
"name" => "Jhon Doe",
"age" => 31,
]
],
"nested" => [
"foo" => "bar"
]
];
var_dump(array_path("customers.0", $data)); //array["name" => ..., "age" => ...]
var_dump(array_path("nested.foo", $data)); //string "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment