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:
// create an array of strings called $fruitBasket:
$fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" );
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:
// create an array of strings called $insurance:
$insurance = array( "life insurance", "auto insurance", "travel insurance", "home insurance", "dental insurance" );
// use the in_array() function to check if "life insurance" is in the array:
if( in_array("life insurance", $insurance) )
echo "life insurance is in the array";
echo "life insurance 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(“life insurance”, $insurance)
in_array() takes two parameters here: firstly the object we’re looking for, in this case “life insurance”, and secondly the array which we’re looking in, $insurance. It then returns a boolean value: true if “life insurance” is in the array, or false if it isn’t.