PHP in_array() Function

PHP in_array() function is “used to check whether a given value exists in an array. It returns TRUE if the given value is found in the array and FALSE otherwise.

Syntax

in_array(search, $array, strict)

Parameters

  1. search(required): It is the value that needs to be searched in an array.
  2. $array(required): It is the array in which we search the value.
  3. strict(optional): If this parameter is set to TRUE, the in_array() function searches for the search string and specific type in the array.

Return value

The in_array() function returns a boolean value, i.e., TRUE if the value is found in the array; otherwise, it returns FALSE.

Visual RepresentationVisual Representation of PHP in_array() Function

Example 1: How to Use in_array() function

<?php

$MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran'];

if (in_array('Bran', $MVP))
{
   echo "Bran has won the Iron Throne";
}
else
{
   echo "Nobody has won the Game of Thrones";
}

Output

Bran has won the Iron Throne

In this example, in_array checks whether the string ‘Bran’ is an element of the array $MVP. Since ‘Bran  is indeed in the array, it returns true.

Example 2: Using strict modeVisual Representation of Using strict mode

<?php

$MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran', '19'];

if (in_array(19, $MVP, true))
{
   echo "19 is there \n";
}
else
{
   echo "Datatype is not matching \n";
}
if (in_array('19', $MVP, true))
{
   echo "19 is there \n";
}
else
{
   echo "Datatype is not matching \n";
}

Output

Datatype is not matching 
19 is there

if (in_array(19, $MVP, true)) checks if the integer 19 is in the $MVP array. It does not find an integer 19 because all values in the array are strings, so returns false.

if (in_array(’19’, $MVP, true)) checks if the string ’19’ is in the $MVP array. It finds a match because there is a string ’19’ in the array, so returns true.

Example 3: in_array() function is case-sensitive

<?php

$MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran'];

if (in_array('BRAN', $MVP))
{
   echo "Bran has won the Iron Throne";
}
else
{
   echo "Nobody has won the Game of Thrones";
}

Output

Nobody has won the Game of Thrones

That’s it.

1 thought on “PHP in_array() Function”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.