- print_r: documentation ( source)
<?php
$arr = [
['one' => 'once',
'two' => ['one' => 'twice', 'two' => 'twice', ['one' => 'thrice']],
'three' => 'once',]
];
$needle = 'one'; // the key we're looking for
$result = pathFinder($arr, $needle);
/**
* function pathFinder() returns the path(s) to a key in an array.
*
* @param array $arr the subject array
* @param string $needle the key we're looking for
*
* @return array the paths leading to the key we're looking for
*/
function pathFinder(array $arr = [], $needle = ''): array
{
static $path = '';
static $paths = [];
foreach ($arr as $key => $value) {
if (is_array($value)) {
$path .= $key . "->";
pathFinder($value, $needle);
} else {
if ($key === $needle) {
$paths[] = $path . $key; // store path
}
}
}
return $paths; // return all found paths to key $needle
}
echo '<pre>';
print_r($result);
echo '</pre>';