How to make empty () accept the value 0

4

I have a registered where I check if the fields are filled, in some of the fields one can only put the digits 0 through 9.

But if the person puts 0 of it as if it had not filled anything.

This is done by checking empty() . A small snippet of verification is there.

}else if (empty($idade)){
    
asked by anonymous 24.06.2014 / 16:25

3 answers

4

You can improve the expression by using something like:

else if (empty($idade) && $idade != 0)

This will check if the age is empty and is not zero. But it's better to consider more specific validation like PHP's is_int .

    
24.06.2014 / 16:31
0

Another form of solution would be:

else if (empty($idade) || count(ltrim($idade," ")) < 1)

What this check does is:

  • Check that the $idade variable is empty;
  • Or if your extension is less than 1 character (not counting spaces)
24.06.2014 / 16:40
0

From what I understand, you want to check if the value is empty with "empty", but you want to accept it if it equals 0.

In this case one would first have to check if the value is equal to 0, since the verification will occur from right to left; otherwise, empty would return true by first checking "0" as an empty value.

I would do it as follows:

$var = 0;

if($var != 0 && empty($var)) {
    echo 'Não é 0 e é vazio';
} else {
    echo 'Isso está aparecendo porque o valor é numérico, igual a 0';
}
    
24.06.2014 / 21:01