note 88047 added to function.array-search

From: Date: Wed, 07 Jan 2009 16:50:03 +0000
Subject: note 88047 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-148924@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 209.41.74.194 Probable Submitter: 168.169.11.198 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/88047 Del: integrated -- https://master.php.net/note/delete/88047/integrated Del: useless -- https://master.php.net/note/delete/88047/useless Del: bad code -- https://master.php.net/note/delete/88047/bad+code Del: spam -- https://master.php.net/note/delete/88047/spam Del: non-english -- https://master.php.net/note/delete/88047/non-english Del: in docs -- https://master.php.net/note/delete/88047/in+docs Del: other reasons-- https://master.php.net/note/delete/88047 Reject -- https://master.php.net/note/reject/88047 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148924) next »