What is the in_array method in PHP?

The in_array method checks if a value is present in an array.

Syntax

in_array(mixed $value, array $haystack, bool $strict = false): bool

Parameters

  • value: The value to be searched for in an array.

  • haystack: The array that will be searched.

  • strict: An optional boolean argument. If we pass true as the value, then the in_array function will also check the types of the value. By default, the value of the strict argument is false.

Return value

The function returns true if value is in the haystack. Otherwise, false is returned.

Code

Example 1

<?php
$learning_platform = array("Udemy", "Udacity", "Educative");
if (in_array("Educative", $learning_platform)) {
echo "Educative is present";
}
if (in_array("Facebook", $learning_platform)) {
echo "Facebook is present";
}
?>

Explanation

In the code above, we create an array with the name learning_platform.

  • We first use the in_array method to check if the Educative string is present in the created array. The in_array method will return true because Educative is present in the array.

  • We then check if the Facebook string is present in the created array. The in_array method will return false because Facebook is not present in the array.

Example 2

<?php
$num = array(1,2);
if (in_array("1", $num)) {
echo "1 is present\n";
}
if (in_array("1", $num, true)) {
echo "1 is present";
} else {
echo "1 is not present";
}
?>

Explanation

In the code above, we create an array with the name num and the values 1 and 2.

$num = array(1,2)

We first check if 1 is present in the array.

in_array("1", $num)

By default, the type of the value to be searched is not checked, so the in_array method will return true.


We then use the in_array method to check if 1 is present in the array. To do this, we set the value as true for the strict argument.

in_array("1", $num, true)

In this case, the type of the value to be searched is also checked, so the in_array method will return false.


Free Resources