blog SyKoHPaTh

Find Match in Array of Objects

Short one today...

Normally, array_search() is awesome for finding a match within an array:

$array = array( "one", "two");
array_search("one", $array); //true

But, in dealing with an array of objects (such as a resultset in a framework), there's not a built-in function that handles this (to my knowledge!). So this function will handle it:

Code Sample:
  1. function search_array_object($needle, $arrayHaystack){
  2. foreach($arrayHaystack as $key=>$objectHaystack){
  3. foreach($objectHaystack as $value){
  4. if($needle == $value){
  5. return $key;
  6. }
  7. }
  8. }
  9. }


So if you have something like this:
$arrayObj[0]->text = "one";
$arrayObj[1]->text = "two";
$arrayObj[2]->text = "three";

You'll get:
$key = search_array_object("two", $arrayObj); // returns "1", the key where it was found




php