Reputation: 2481
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...
Upvotes: 3
Views: 10858
Reputation: 131871
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
.
Upvotes: 2
Reputation: 86356
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])
Upvotes: 2
Reputation: 400972
in_array()
will search in the values -- and not the keys.
You should either :
array_key_exists()
: if (array_key_exists(15, $rsvp_array)) {...}
isset()
to test whether a certain key is set : if (isset($rsvp_array[15])) {...}
array_keys()
to get the keys, and use in_array()
on that array of keys.Upvotes: 17