Nick Rolando
Nick Rolando

Reputation: 26177

Checking if value exists in array with array_search()

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.

Upvotes: 3

Views: 14552

Answers (3)

James Valeii
James Valeii

Reputation: 482

As an alternative to ===, !==, and in_array(), you can use array_flip():

$arr = [3,4,5,6,7];

$rra = array_flip($arr);

if( $rra[3] !== null ):

  var_dump('Do something, '.$rra[3].' exists!');

endif;

This is not fewer lines than the accepted answer. But it does allow you to get position and existence in a very human-readable way.

We want to find out if int 3 is in $arr, the original array:

array (size=5)
0 => int 3
1 => int 4
2 => int 5
3 => int 6
4 => int 7

array_flip creates a new array ($rra) with swapped key-value pairs:

array (size=5)
3 => int 0
4 => int 1
5 => int 2
6 => int 3
7 => int 4

Now we can verify the existence of int 3, which will (or will not be) a key in $rra with array_key_exists, isset, or by enclosing $rra[3]` in an if statement.

Since the value we are looking for could have an array key id of 0, we need to compare against null and not rely on evaluating 0 to false.

You can also make changes to the original array, should that be the use case, because if $rra[3] isn't null, $rra[3] will return what is the key (position 0, in this case) for the value in the original array.

if ( $rra[3] !== null ):
  // evaluates to: unset( $array[0] );
  unset( $arr[ $rra[3] ] );
endif;

This operation works just as well if you're working with an associative array.

Upvotes: 0

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22162

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
}

Upvotes: 15

Abhi Beckert
Abhi Beckert

Reputation: 33369

As an alternative to === and !==, you can also use in_array:

if (in_array($needle, $haystack))

Upvotes: 8

Related Questions