Finding Items in an Array with PHP

The problem: we have an array of items in PHP and we want to find out if a specific item is in the array. In code we can define the array as:

IE we have an array called $fruitBasket which contains 5 strings, each of which is the name of a fruit. We want to find out if there is an Apple in the $fruitBasket - is there an element "Apple" in the array?
We do this with the following code:

PHP:
  1. <?
  2. // create an array of strings called $fruitBasket:
  3. $fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" );
  4. // use the in_array() function to check if "Apple" is in the array:
  5. if( in_array("Apple", $fruitBasket) )
  6. {
  7.   echo "Apple is in the array";
  8. }
  9. else
  10. {
  11.   echo "Apple is not in the array";
  12. }
  13. ?>

This code uses the in_array() method to check if the element "Apple" exists in the array $fruitBasket:
in_array("Apple", $fruitBasket)

in_array() takes two parameters here: firstly the object we're looking for, in this case "Apple", and secondly the array which we're looking in, $fruitBasket. It then returns a boolean value: true if "Apple" is in the array, or false if it isn't.

References: php.net manual: in_array() function

If you have a low-traffic website, consider joining the Money4Banners advertising network. They will pay you £10 + £5 each month for displaying a small advert on three of your pages, regardless of traffic. American webmasters are welcome, and since £10 == $20, you make more!


No Responses to “Finding Items in an Array with PHP”  

  1. No Comments

Leave a Reply

You must log in to post a comment.


Categories