will-ashworth
10/27/2016 - 6:46 PM

PHP doesn't make it very easy to recursively look inside a multi-dimensional array. These couple methods make that easier.

PHP doesn't make it very easy to recursively look inside a multi-dimensional array. These couple methods make that easier.

/**
 * Recursively look for Needle in Haystack
 * @param $needle
 * @param $haystack
 * @returns boolean
 */
function in_array_r($needle, $haystack, $strict = true) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
 
    return false;
}
$simpsons = array('bart', 'lisa', 'homer');
echo in_array_r("bart", $simpsons) ? 'found' : 'not found';