0

I have an variable called $vars which contains an array that is submitted with form:

Array
(
    [name] => Sample Name
    [email] => [email protected]
    [job_role] => 
    [telephone_number] => telephone number
    [comment] => comment
)

How can I check if job_role index is containing a value?


I tried:

if (in_array('', $vars)){
  echo "Job role can't be empty";
} else {
  echo "Job role submitted";
}

But this works on the whole array and not only the job_role index.

Also, I tried:

if (isset($vars['job_role'])){
  echo "match found";
} else {
  echo "nothing there";
}

But it was returning "match found" even when I didn't submit anything...

Why is isset() always returning true?

7
  • ehemmm... why downvote? Commented Apr 17, 2018 at 12:30
  • The answer to the question "can anyone help" is "yes", but it is probably not the question you actually want to ask. Questions here benefit from being focussed and specific. Commented Apr 17, 2018 at 13:00
  • Questions that ask "please help me" tend to be looking for highly localized guidance, or in some cases, ongoing or private assistance, which is not suited to our Q&A format. It is also rather vague, and is better replaced with a more specific question. Please read Why is “Can someone help me?” not an actual question?. Commented Apr 17, 2018 at 13:00
  • 2
    @BareFeet isset() checks if the value defined (is set), not it is empty. In your code $vars['job_role'] is probably an empty string, so, it's defined, but it's empty. Commented Apr 17, 2018 at 13:10
  • 1
    @halfer I'm sorry for making you an effort to edit my question again. The reason why I asked "Can anyone help" was just because I wanted to be polite. After reading the meta post, I understand why I should not do it. I will keep this in mind. Thank you. Also, I reworded my question to make it more clear what I was asking. I hope someone will take it positively now :) Commented Apr 18, 2018 at 8:56

1 Answer 1

3

You can use empty() to check if the entry is not empty:

if (empty($vars['job_role'])) {
    echo "Job role can't be empty";
} else {
    echo "Job role submitted";
}

Because isset() checks if the value defined (is set), not it is empty. In your code $vars['job_role'] is probably an empty string, so, it's defined, but it's empty.

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

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.