当前位置: 动力学知识库 > 问答 > 编程问答 >

arrays - 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, i.e.:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: