Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[PHP]: What does array_search() return if nothing was found?

Tags:

What does array_search() return if nothing was found?

I have the need for the following logic:

$found = array_search($needle, $haystack);  if($found){   //do stuff } else {   //do different stuff } 
like image 227
Derek Adair Avatar asked Apr 05 '10 22:04

Derek Adair


People also ask

What does array_search return in PHP?

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

Which of the following function are used to find a value in an array?

Explanation: The array_search() function searches an array for a specified value, returning its key if located and FALSE otherwise.


2 Answers

Quoting the manual page of array_search() :

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


Which means you have to use something like :

$found = array_search($needle, $haystack);  if ($found !== false) {     // do stuff     // when found } else {     // do different stuff     // when not found } 

Note I used the !== operator, that does a type-sensitive comparison ; see Comparison Operators, Type Juggling, and Converting to boolean for more details about that ;-)

like image 122
Pascal MARTIN Avatar answered Oct 05 '22 00:10

Pascal MARTIN


if you're just checking if the value exists, in_array is the way to go.

like image 31
user187291 Avatar answered Oct 04 '22 22:10

user187291