0' as a string with empty() in PHP
You cannot make empty() take it. That is how it was designed. Instead you can write an and
statement to test:
if (empty($var) && $var !== '0') {
echo $var . ' is empty';
}
You could use isset
, unless of course, you want it to turn away the other empties that empty
checks for. How to convert empty string to zero?
The only real way is to typecast:
<?php
$str = '';
echo (int)$str;
However, if this is dynamically assigned then you'll have to use an if statement. But fear not, ternary exists:echo (empty($str) ? 0 : $str);
With the thanks of Dharman, we can Elvis it up a bit:echo $str ?: 0;
Though, note that if $str
is not defined PHP will throw a undefined notice. For that reason either stick to ternary or ensure the variable is declared before usage. In php, is 0 treated as empty?
http://php.net/empty
Note that this is exactly the same list as for a coercion to BooleanThe following things are considered to be empty:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
- NULL
- FALSE
- array() (an empty array)
- var $var; (a variable declared, but without a value in a class)
false
. empty
is simply !isset($var) || !$var
. Try isset
instead. empty() returns true if a zero float value was passed as string
This zero/empty condition works the same way in both PHP 7 and 8 versions:
if (empty($var) || (is_numeric($var) && (float)$var == 0))
It checks if $var is any of the following:not set, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", or (array)[]
And to substitute empty():
// Checks if variable is not set, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", (array)[], or array with nil nodes
function nil(&$var) { // https://www.dictionary.com/browse/nil
return (empty($var) || (is_numeric($var) && (float)$var == 0));
}
To be used like:if (nil($var)) {
echo 'The value is either not set, an empty string, empty array, null, or equals zero.';
}
It can be expanded to check subnodes for arrays as well: // Checks if variable is not set, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", (array)[], or array with nil nodes
function nil(&$var) {
if (is_array($var)) {
foreach ($var as $node) {
if (!nil($node)) return !1;
}
}
return (empty($var) || (is_numeric($var) && (float)$var == 0));
}
Empty string comparison to zero gives different result in PHP 8 than in previous versions
You are right, this is a major change.
As with any version upgrade, you can find a guide to Migrating to PHP 8.0 in the official PHP manual. If you click on Backward Incompatible Changes you will see that this change is the very first thing on that page:
Non-strict comparisons between numbers and non-numeric strings now work by casting the number to string and comparing the strings.As well as an example in the next sentence, there is a before-and-after comparison table which includes the exact example you gave:
Comparison:If you have code that was relying on the old behaviour, you will need to update it to be more explicit about the values expected. For instance, all of the following work in all versions of PHP:0 == ""
; Before:true
; After:false
if ( $value === 0 || $value === "" ) { ... }
if ( (string)$zero === "" ) { ... }
if ( (int)$emptyString === 0 ) { ... }
For more background on the change, you can read the original proposal here: PHP RFC: Saner string to number comparisons PHP: what's an alternative to empty(), where string 0 is not treated as empty?
The answer to this is that it isn't possible to shorten what I already have.
Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.
PHP: using empty() for empty string?
You should not use empty
(or isset
) if you expect $foo
to exist. That means, if according to your program logic, $foo
should exist at this point:
if ($foo === '')
Then do not do any of these:if (isset($foo))
if (empty($foo))
These two language constructs suppress error reporting for undefined variables. That's their only job. That means, if you use isset
or empty
gratuitously, PHP won't tell you about problems in your code. For example:$foo = $bar;
if (empty($føø)) ...
Hmm, why is this always true
, even when $bar
contains the expected value? Because you mistyped the variable name and you're checking the value of an undefined variable. Write it like this instead to let PHP help you:if (!$føø) ...
The condition itself is the same,Notice: undefined variable føø on line ...
== false
(!
) and empty
produce the same outcome for the same values.How exactly to check for an empty string depends on what values you do or don't accept. Perhaps $foo === ''
or strlen($foo) == 0
is the check you're looking for to ensure you have a string with something in it.
float 0 returns as empty string in php
This is because in PHP the following expressions are true:
0 == ""
0.0 == ""
not because $empty
here is the empty string ""
.You can perform a typed equality check using ===
, and these expressions will appear false, as expected:
0 === ""
0.0 === ""
Related Topics
Create a Joomla! Article Programmatically
How to Return Only Named Groups with Preg_Match or Preg_Match_All
PHP Sort a Multidimensional Array by Number of Items
Having Trouble Writing to a File with PHP on Ubuntu
How to Use a Class Method as a Callback Function
Expression Is Not Allowed as Field Default Value
Xpath Get Attribute Value in PHP
How to Run a Whois Lookup with PHP or Python
How to Remove Exif from a Jpg Without Losing Image Quality
How to Convert Emoji from Unicode in PHP
Symfony2:Two Forms in a Same Page
PHP - Display a 404 Error Without Redirecting to Another Page
Symfony 2.7 Cache:Clear Command Checks Every Database Connection
Change Mime Type of Output in PHP