note 88047 deleted from function.array-search by levim
| From: | levim@php.net | Date: | Mon, 24 Feb 2014 22:42:52 +0000 |
| Subject: | note 88047 deleted from function.array-search by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-198690@lists.php.net to get a copy of this message | ||
Note Submitter: tim_hauber at stev dot net
----
A slight addition to array_search_recursive by Alireza Eliaderani below. The original searched the
entire haystack, even if it found the needle at the beginning of the haystack. I must admit I had a
little trouble wrapping my head around how to break out of a loop in a recursive function. This
version returns after first occurrence of needle. changes commented.
<?php
function array_search_recursive($needle, $haystack){
$path=array();
foreach($haystack as $id => $val)
{
if($val === $needle) {
$path[]=$id;
break;
# ^^this breaks out of loop when it finds needle
} else if(is_array($val)){
$found=array_search_recursive($needle, $val);
if(count($found)>0){
$path[$id]=$found;
break;
# ^^this breaks out of loop when recursive call found needle
}
}
}
return $path;
}
?>