Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if value exists in array with array_search()

Tags:

php

If 0 could be a possible key returned from array_search(), what would be the best method for testing if an element exists in an array using this function (or any php function; if there's a better one, please share)?

I was trying to do this:

if(array_search($needle, $haystack)) //...

But that would of course return false if $needle is the first element in the array. I guess what I'm asking is is there some trick I can do in this if statement to get it to behave like I want it? I tried doing these, but none of them worked:

$arr = array(3,4,5,6,7);

if(array_search(3, $arr) != false)  //...

if(array_search(3, $arr) >= 0)  //...

Appreciate the help.

like image 349
Nick Rolando Avatar asked Jun 19 '26 10:06

Nick Rolando


1 Answers

This is the way:

if(array_search(3, $arr) !== false)

Note the use of the === PHP operator, called identical (not identical in this case). You can read more info in the official doc. You need to use it because with the use of the equal operator you can't distinguish 0 from false (or null or '' as well).

A better solution if you find the match and want to use the integer value is:

if (($pos = array_search(3, $arr)) !== false)
{
   // do stuff using $pos
}
like image 135
Aurelio De Rosa Avatar answered Jun 21 '26 01:06

Aurelio De Rosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!