PHP:array_search返回null

I have a regular array that contains numbers from 1 to 14 that is generated by retrieving INTs from a SQL result column.

Using another query I'm returning another INT.

I'm searching for this INT in my array.

$key = array_search("$roomNb", $freeRooms);

However when I try to echo this key nothing appears. It is empty.

If I echo $freeRooms using a loop I get:

1
2
3
4
5
6
7
8
9
10
11
12
14

If I echo $roomNb I get

5

So I can't understand why I'm not getting anything in return. I should be expecting a key of 4 no? What could be causing this?

Most likely $key is false which when sent to echo will appear as nothing. Instead you should use var_dump to determine the value of $key

False is returned from array_search when the needle is not found

Null is only returned when the parameters you pass to array_search are invalid

http://php.net/manual/en/function.array-search.php

Test this code here using http://writecodeonline.com/php/:

echo false;
echo null;
var_dump(false);
var_dump(null);

$code = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
$roomNb = 5;

var_dump(array_search("$roomNb", $code));

Should work just fine. echo will output nothing. var_dump will output stuff. And the key is found at 4.

Assuming that your array will always contain contiguous numbers, and you can verify that your second SQL call returns one of those numbers, I would say something like

$value = $freeRooms[$roomNb] 

I'm personally unfamiliar with how array_search executes, however if you wanted to write your own, I assume it would look something like this

function IndexOf($searchValue,$array)
{
    $i = 0;
    for( $i = 0; $i < count($array); $i++ ) 
        if( $array[$i] == $searchValue )
            return $i;
}