0

I have an array that's accessed via $request (this is not the same as $_REQUEST). The array print_r's out as

Array
(
    [num_days] => 30
    [customer_id] => 5
)

The num_days key may or may not exist (it can be any number of things.) I need to test to see if the key exists. I've tried this:

if(array_key_exists($request['num_days'], $request)) {
    echo "num_days exists";
}
else {
    echo "num_days doesn't exist";
}

This always hits the else. Am I doing this wrong? Is num_days not considered a key? If not, how can I test for the existence of that element (NOT the value of it, but whether it exists at all)?

4
  • 6
    array_key_exists('num_days', $request) Commented Jan 15, 2013 at 16:10
  • @DanielM: isset() and array_key_exists() are not totally the same. If the value was set, but was NULL, then isset() would return false, but array_key_exists() would return true. Commented Jan 15, 2013 at 16:11
  • 1
    Thank you, @Orbling. If you want to post as an answer, I'll accept. Commented Jan 15, 2013 at 16:12
  • 1
    No need, simple misunderstanding, one term answer. No idea why it was marked down, the question and mistake may be simple, but there was nothing wrong with it. Negative marks are not supposed to be punishment for lack of knowledge. Commented Jan 15, 2013 at 16:13

2 Answers 2

2

Use either array_key_exists('num_days', $request) or isset($request['num_days'])

What you are doing is wrong and just checks if the value of that array elements exists as a key.

Sign up to request clarification or add additional context in comments.

Comments

1

What you have done is wrong

array_key_exists — Checks if the given key or index exists in the array

Your code with array_key_exists Read more

if(array_key_exists('num_days', $request)) {
    echo "num_days exists";
}
else {
    echo "num_days doesn't exist";
}

Alternative method with isset Read more

   if(isset($_REQUEST['num_days'])) {
        echo "num_days exists";
    }
    else {
        echo "num_days doesn't exist";
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.