Find an Item in an Array (PHP)

On occasion, I’m sure you’ve found yourself in a position where you need to find an item inside of an array. PHP offers a very simple method to do just that. The array_search function lets you search for the item and then tells you what the index for that item is. This function works with numerically indexed arrays and with associative arrays.

Let’s use a little sample code to show you just how this function works. First, let’s build a simple, numerically indexed array.

$arr = array('apple','orange','banana','donut');

Next, we’ll use the array_search function to find out what the index is for “banana.”

$b = array_search('banana',$arr);

The new $b variable will now be set to the number 2 (which, as you can see, is the index of the string “banana” in our array).

Obviously, that’s a short, simple array, and it’s built manually, so you probably have a pretty good idea which numerical index matches up with which item in the array. However, let’s imagine that you retrieved a list of 200 customer names from a database and you need to figure out where a specific customer name appears in the array. The array_search function can be very helpful in instances like that.

Now, let’s imagine you simply need to find out if an item exists inside of an array. You can use the array_search function to do so (it will return boolean false if the item is not found), but you don’t really need to. Instead, PHP offers two simple functions to figure out whether or not items exist inside of an array.

The first function is the in_array function. The in_array function simply searches an array to see if the item exists. If the item is found, it returns boolean true; if not, it returns boolean false. Let’s look at some sample code, using the same array we built above.

if(in_array('banana',$arr)) {
echo 'We found a banana';
}
else {
echo 'We did not find any bananas';
}

The second function is array_key_exists. This function, rather than checking to see if an item exists inside of an array, checks to see if a specific key exists as an index in the array. While it’s possible to use this function with consecutively numerically indexed arrays, it generally doesn’t make much sense. Therefore, in order to show some sample code, I’ll go ahead and build a new, associative array.

$arr = array('fruit'=>'banana','vegetable'=>'carrot','sauce'=>'ranch','pastry'=>'donut');
if(array_key_exists('pastry',$arr)) {
echo 'Our pastry is set to '.$arr['pastry'];
}
else {
echo 'We did not find any pastries in our array.';
}

One Response

  • Me

    Thanks man, I was looking for this.

Post Your Comment

Your email address will not be published.