How To Find Items in PHP Arrays

1 minute read

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:

<?php 
  // create an array of strings called $fruitBasket: 
  $fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" ); 
?>

So 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 fruit basket - i.e. is there an element "Apple" in the $fruitBasket array?

We do this with the following code:

<?php
  // create an array of strings called $fruitBasket:
  $fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" );
  // use the in_array() function to check if "Apple" is in the array:
  if( in_array("Apple", $fruitBasket) ) {
    echo "Apple is in the array";
  } else {
    echo "Apple is not in the array";
  }
?>

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

The function 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

Tags:

Categories:

Updated: