This question already has an answer here:
I try to find a value in an array, no matter how deep that array is or what "structure" it may have. But my approach doesn't find all values. I think I get the recursion wrong, but I don't know.
$haystack = array(
'A',
'B' => array('BA'),
'C' => array('CA' => array('CAA')),
'D' => array('DA' => array('DAA' => array('DAAA')))
);
function array_find($needle, array $haystack) {
foreach ($haystack as $value) {
if (is_array($value)) {
if (in_array($needle, $value)) {
return true;
} else {
return array_find($needle, $value);
}
} else {
if ($value == $needle) {
return true;
}
}
}
return false;
}
$find = array('A', 'BA', 'CAA', 'DAAA');
foreach($find as $needle) {
if (array_find($needle, $haystack)) {
echo $needle, " found".PHP_EOL;
} else {
echo $needle, " not found".PHP_EOL;
}
}
</div>