3

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...

1
  • do{}while() is not suitable for fetching data, always use while(){} Commented Apr 13, 2011 at 10:31

3 Answers 3

17

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.
Sign up to request clarification or add additional context in comments.

1 Comment

@Felix : indeed ; I've edited my answer to say it's a bad idea -- and it's now the third proposal (I've added isset as a second proposal, so the last one is the 'bad' one)
2

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])

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.