Check empty variable in PHP

Asked

Viewed 5,062 times

0

When I check an empty variable in PHP I am using function denial Empty(), works, but not yours if this is correct and would like to know if there are other ways to do this?

if (!empty($numer)) {    
   echo "<h2>O numero informado foi  " . $numer . "</h2>";    
}

4 answers

3

If your variable should be a number, do not use empty. Just read what the documentation says:

Value Returned

Returns FALSE if var exists and is not empty, and does not contain a zeroed value. Otherwise it will return TRUE.

What is seen below is considered empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a floating point)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a declared variable but no value)

That is, if the variable is equal to 0, empty will return true even if a valid number.

If, in any way, the variable can arrive at being set, use the isset to verify its existence and is_numeric to check if it is numerical:

isset($number) and is_numeric($number)

But the only situation that I imagine, at the moment, that it is plausible to verify the existence of the variable is when it comes by an HTTP request and in this case the ideal is to do:

$number = filter_input(INPUT_GET, 'number', FILTER_VALIDATE_INT);

Thus, $number will always be set and will be equal to the value, if the given value was a number, false if the filter fails or null if the variable was not set in $_GET.

2

It has no problem to use empty(), but if(!$numer) also works. The good of empty() is that it validates if the variable in question is null, empty or false, which is good depending on your case.

1

That page shows the comparison between the functions Empty(),is_null(),isset()... You can verify the one that best applies to your case

inserir a descrição da imagem aqui

0

You can do it this way:

<?php
$numer = $_GET['num'];
if(!is_numeric($numer) or !$numer or $numer == 0){

      echo "<h2>Nenhum número foi informado</h2>";
    }else{
    echo "<h2>O numero informado foi  " . $numer . "</h2>";
    }

This way if the value of $numer is not numerical, empty or has a value of 0, it will inform that no number has been informed. Otherwise, it will present the value of the variable.

  • 1

    What if $numer (sic) is equal to 0?

  • True friend. I hadn’t thought of that hypothesis, I’ll add a new condition to the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.