/ p>
if (!empty($numer)) {
echo "<h2>O numero informado foi " . $numer . "</h2>";
}
/ p>
if (!empty($numer)) {
echo "<h2>O numero informado foi " . $numer . "</h2>";
}
It's okay to use empty()
, but if(!$numer)
also works.
The good thing about empty()
is that it validates if the variable in question is null, empty or false, which is fine depending on your case.
If your variable must be a number, do not use empty
. Just read what the documentation says:
Return Value
Returns
FALSE
if var exists and is not empty, and not contain a reset value. Otherwise it will returnTRUE
.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 it is a valid number.
If the variable can somehow be defined, use isset
to check its existence and is_numeric
to check if it is numeric:
isset($number) and is_numeric($number)
But the only situation that I imagine at the moment is 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 value entered was a number, false if the filter fails or null if the variable was not set to $_GET
.
This page shows the comparison between empty (), is_null (), isset () ... You can check the one that best applies to you.
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>";
}
In this way, if the value of $ numer is not numeric, is empty or has a value of 0, it will inform you that no numbers have been entered. If instead, it will display the value of the variable.