2

I'm using PHP in my project and when any form is submitted I need to check if the input it not empty, so I use something like this:

if(empty($myVar)) {
    echo "Error";
} else {
    echo "success";
}

But this doesn't seem to be working as I want, so If the user enter empty space like " " so between the quotation is nothing but emptiness, but still PHP showing success message instead of error message.

I used isset($var) also, but its the samething, not working as I need.

What could be the problem? and How to solve it?

1
  • 2
    empty(trim($myVar)) and you are fine. And since we are in it-world you mean more: eyesight emptiness Jan 30, 2017 at 15:38

4 Answers 4

6

Use trim function, which removes spaces in the beginning and in the end of a string:

if(empty(trim($myVar))) {
    echo "Error"
} else {
    echo "success";
}
3
  • Thank So much, you saved my day :) But I have a quick question, why empty function is not useful in this state? why it doesn't count space as a real character? Or what exactly is happening in this function? Jan 30, 2017 at 15:42
  • Here's a manual page php.net/manual/en/… It describes which values are considered empty
    – u_mulder
    Jan 30, 2017 at 15:43
  • @Maohammed Hayder Very important and helpfull tables php.net/manual/en/types.comparisons.php Jan 30, 2017 at 15:45
3
echo empty(trim($myVar)) ? 'Error' : 'success';
0
2

If you want to trim all fields from $_POST, use the following:

$_POST = array_map("trim", $_POST);

Then you can just check with empty().

But this is only useful if you have a couple of fields. For just one, you should follow the direct way with empty(trim($var))

2

I would suggest you should first trim the $myVar before checking the emptyness as follows

if(empty(trim($myVar))) {
    echo "Error";
} else {
    echo "success";
}

What this will do is will remove any leading or trailing whitespaces from variable $myVar and then check if the variable is empty or not.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.