Monthly Archives

July 2011

PHP Function in_array_by_id Search an array for an elements location or index

It seems crazy that there isn’t a function that already does this very simple task, namely, search an array for an element, and return its index (i.e. location) in that array.

  • in_array() will tell you if the element is in the array, but not where it is.
  • search_array() will search an associative array, but not a normal array.

So here is an example array with 7 string elements and what I want to be able to do.


> $myarray = array('Home', 'Control Panel', 'Members', 'Todays Figures', 'History', 'Listing', 'Add New Offer');
> echo in_array_by_id($myarray, 'Control Panel');
2

We passed two variables to our currently non-existent function in_array_by_id(). The array being searched and the element whose index we are search for (i.e. the proverbial needle in the haystack) respectively.

So I put together this sadly simple function:

 function in_array_by_id($array, $needle)
 {
     $array_index = 0;
     foreach ($array as $element)
     {
         if ($needle == $element)
         {
              return $array_index;
         }
         $array_index++;
     }
     return NULL; 
 }

As you can see, it returns a NULL value if the element is not found. So when doing checks you’ll want to remember to use the !== or === since you will be dealing with return values of 0 when the element is the first in the array.