PHP in_array Vs array_search

Alam Riku
2 min readSep 9, 2020

--

Assalamualaikum , I am going to explain the difference between mostly used PHP built-in function. What I faced when implementing these function on a particular web application.

in_array

in_array — Checks if a value exists in an array

in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool

Searches for needle in haystack using loose comparison unless strict is set.

needle : The searched value.If needle is a string, the comparison is done in a case-sensitive manner.

haystack: The array.

strict: If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Return Values : Returns TRUE if needle is found in the array, FALSE otherwise.

<?php
$os = array(“Mac”, “NT”, “Irix”, “Linux”);
if (in_array(“Irix”, $os)) {
echo “Got Irix”;
}
if (in_array(“mac”, $os)) {
echo “Got mac”;
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

array_search()

array_search — Searches the array for a given value and returns the first corresponding key if successful

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

Searches for needle in haystack.

Return Value: Returns the key for needle if it is found in the array, FALSE otherwise.

<?php
$arr = array(“nice”,”car”,”none”);
var_dump(array_search(“car”, ($arr)));

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

non-Boolean value which evaluates to FALSE

$array = [“a”,”b”,”c”,”d”];
$key = array_search(“a”, $array); //$key = 0
if ($key)
{
//even a element is found in array, but if (0) means false
//…
}
//the correct way
if (false !== $key)
{
echo $key;
}

OR

if(in_array(‘a’, $array)){

$key = array_search(‘a’, $array)

unlink($array[$key]);

}

Conclusion:

array_search return key if found else return false

array_search: If needle is found in haystack more than once, the first matching key is returned.

in_array return true if found else return false

If you’re working with very large 2 dimensional arrays (eg 20,000+ elements) it’s much faster to do this…

<?php
$needle = ‘test for this’;

$flipped_haystack = array_flip($haystack);

if ( isset($flipped_haystack[$needle]) )
{
print “Yes it’s there!”;
}
?>

array_flip — Exchanges all keys with their associated values in an array

Remember to only flip it once at the beginning of your code though!

--

--

Alam Riku
Alam Riku

Written by Alam Riku

I am a learner who dives into the ocean of knowledge realm.

No responses yet