Skip to content

Difference between in_array() and array_search() in PHP

in arrayvsarra search

in_array

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

The in_array() function searches for a specific value in an array. If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

Example

<?php
$diary = array("D", "e", "v", "l", "o", "p", "e", "r");
if (in_array("v", $diary))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>

array_search

Syntax :  array_search($value, $array, strict_parameter)

The array_search() function searches an array for a specific value and returns the key. The function returns the key for val if found in the array. Returns FALSE if not found. If val is found more than once in the arr array, the first matching key is returned.

Example

<?php
   $marks = array("maths"=>60,"english"=>70,"biology"=>60,"hindi"=>65);
   echo array_search(70,$marks,true);
?>

Output

english

Conclusion

In this article we learn difference between in_array and array_search. Which is very important interview question which asking most of the time on the interview. Do you have any question freel free comment your feedback.