PHP search in array



In this tutorial we are going to learn how to search in array. In PHP we can use mainly two functions for this

  • in_array()
  • array_search()

PHP array search using in_array() function
This function will check the specified value is present in an array or not. It will return TRUE if the value is present in array, otherwise it will return FALSE
Its Syntax will be :
in_array(Value to search , array , strict Boolean);
First parameter will be the value to search in an array
Second parameter will the array to search
Third parameter is optional. If we specify it as TRUE function will check the type of value also. Type of the value should also match in the array value, then only it will return TRUE. By default this strict parameter will be FALSE ( wont check the type )
Now look at a sample PHP program using in_array search

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="25";
if (in_array($key_search,$age))
{
echo "VALUE EXIST without strict parameter search";
}
else
{
echo "VALUE NOT PRESENT without strict parameter search";
}
echo "<BR>";
if (in_array($key_search,$age,TRUE))
{
echo "VALUE EXIST with strict parameter search";
}
else
{
echo "VALUE NOT PRESENT with strict parameter search";
}
?>

Its output will be :

VALUE EXIST without strict parameter search
VALUE NOT PRESENT with strict parameter search

In this case we can see that without strict parameter function found the value in array. But when we used the strict parameter it will check the type also. Here we declared the value to search as a string , and in array the value is in type integer. So no match is there and the function will return FALSE.

PHP array search using array_search() function

This function will search for the specified value in an array and will return the corresponding key of the value if the search is successful.
Its syntax also similar to in_array:
array_search(Value to search , array , strict Boolean);

Now look at a sample PHP program using array_search function :

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="25";
if (array_search($key_search,$age))
{
echo "VALUE EXIST without strict parameter search and its key is ".array_search($key_search,$age);
}
else
{
echo "VALUE NOT PRESENT without strict parameter search";
}
echo "<BR>";
if (array_search($key_search,$age,TRUE))
{
echo "VALUE EXIST with strict parameter search and its key is ".array_search($key_search,$age,TRUE);
}
else
{
echo "VALUE NOT PRESENT with strict parameter search";
}
?>

Its output will be :

VALUE EXIST without strict parameter search and its key is Binu
VALUE NOT PRESENT with strict parameter search

Difference between these two functions:

  • array_search function will return the key or index
  • in_array function will return TRUE or false according to search match