In this article, you will learn how to search for a value in an array. The in_array method in PHP searches the specified value. If the value exists in the array, it returns true, otherwise false.
Note: If the search parameter is a string and the type parameter is set to true, the in_array function will perform a case-sensetive search.
What is the syntax of the in_array function in PHP?
in_array(search, array, type)
Parameter | Description |
---|---|
search | The value to search in the array – Required |
array | The array to search the value in – Required |
type | If the search parameter is a string and the type parameter is set to true, the in_array function will perform a case-sensetive search – Optional |
Examples of the in_array function
Example 1. Search the specified value in the given array.
<?php
$members= array("Jawad", "Ahmad", "Sumerina", "ACS");
if (in_array("Ahmad", $members))
{
echo "Member found";
}
else
{
echo "Member found";
}
?>
Example 2. This example shows the in_array function using all the parameters.
<?php
$members= array("Jawad", "Ahmad", "Sumerina", "ACS", 39);
if (in_array("23", $members, TRUE))
{
echo "Element found<br>";
}
else
{
echo "Element not found<br>";
}
if (in_array("Jawad",$members, TRUE))
{
echo "Element found<br>";
}
else
{
echo "Element not found<br>";
}
if (in_array(23,$members, TRUE))
{
echo "Match found<br>";
}
else
{
echo "Match not found<br>";
}
?>