简体   繁体   中英

PHP in_array function, why this doesn't work?

I have this array, generated from a database:

do {
    $rsvp_array[$row_rsRSVP['rsv_guest']] = array(
        'id' => $row_rsRSVP['rsv_id'],
        'guest' => $row_rsRSVP['rsv_guest'],
        'confirmed' => $row_rsRSVP['rsv_confirmed']
    );
} while ($row_rsRSVP = mysql_fetch_assoc($rsRSVP));

It's vey fine, with print_r() I get this:

Array
(
    [1] => Array
        (
            [id] => 1
            [guest] => 1
            [confirmed] => 1
        )

    [15] => Array
        (
            [id] => 2
            [guest] => 15
            [confirmed] => 0
        )

    [5] => Array
        (
            [id] => 3
            [guest] => 5
            [confirmed] => 1
        )

    [10] => Array
        (
            [id] => 4
            [guest] => 10
            [confirmed] => 1
        )

    [6] => Array
        (
            [id] => 5
            [guest] => 6
            [confirmed] => 0
        )

)

So I know that the array is working.

Now I need to see if a number is in the main array, ie:

if (in_array(15, $rsvp_array)) { echo 'OK'; }

And well, this doesn't work! Number 15 is the second key of the array, but no luck! Where am I wrong? Thanks in advance for the answers...

in_array() will search in the values -- and not the keys.

You should either :

  • use array_key_exists() : if (array_key_exists(15, $rsvp_array)) {...}
  • or use isset() to test whether a certain key is set : if (isset($rsvp_array[15])) {...}
  • or (bad idea) use array_keys() to get the keys, and use in_array() on that array of keys.

Probably you are looking for array_key_exists in_array used to check if the value is in array not for key.

if (array_key_exists(15,$rsvp_array))
{
  echo "ok";
}

or check it with isset

isset($rsvp_array[15])

in_array() are only looking at the values of an array, but you want to know, if a specific key is set

if (array_key_exists(15, $rsvp_array)) { echo 'OK'; }

or

if (isset($rsvp[15])) { echo 'OK'; }

The second one is sufficient in most cases, but it doesnt work, if the value is null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM