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?

Maohammed Hayder
  • 505
  • 3
  • 7
  • 22

4 Answers4

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";
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • 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? – Maohammed Hayder Jan 30 '17 at 15:42
  • Here's a manual page http://php.net/manual/en/function.empty.php#refsect1-function.empty-returnvalues It describes which values are considered empty – u_mulder Jan 30 '17 at 15:43
  • @Maohammed Hayder Very important and helpfull tables http://php.net/manual/en/types.comparisons.php – JustOnUnderMillions Jan 30 '17 at 15:45
3
echo empty(trim($myVar)) ? 'Error' : 'success';
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))

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
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.