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');

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;
     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.

Belisarius Smith consults as a software engineer, cloud engineer, and security adviser. He has a BSBA in Security Management and is currently completing graduate studies in the Engineering Department at Penn State University with a Masters of Software Engineering. When he isn't traveling, mountain climbing, or reading, he spends his spare time on personal side projects and studies.

Leave a Reply