Why I avoid using empty() in PHP? A Closer Look
azizdev.medium.com
azizdev.medium.com
Use isset if you want to see if the variable is set, you should never be casting client input unless it’s coming from query params (or form post I guess but at that point use JSON).
“empty” is a useful tool, provided you take into account things like “is this allowed to be 0/empty-string/etc”.
Lastly:
> After a lengthy debugging session, we realized that empty() was treating 0 as "empty", causing our validation to fail unexpectedly.
Lengthy? To notice an empty check failing? Look, the codebase I work on has its warts, all older codebases do, but unless you have no XDebug, forgot how to log to file or echo to the client, and/or aren’t capable of searching a codebase for the error you got and tracing it back from there then I can’t believe that would be a “Lengthy” process to track down. Even if you are returning a generic error to the client, surely you are logging the real error to a log somewhere?
we had some errors that were happening to only one client and noone could reproduce that.
I don't know enough PHP.
Does isset return true or false if I set a string variable to "" before I call isset?
Example:
$myVar = null;
var_dump(isset($myVar)); // false
$myVar = '';
var_dump(isset($myVar)); // true
$myVar = '0';
var_dump(isset($myVar)); // true
$myVar = 0;
var_dump(isset($myVar)); // true
If you have a property on a class that was never given a value it will also return `false`: class MyClass {
public $myProp;
function myFunction() {
var_dump(isset($this->myProp)); // false
}
}I think the problem is finding a short name for a little complex functionality
isset is like is_null but one thing isset can do is look at a whole chain (class props or associate array keys) and not blow up.
What I mean by that is you can do
$test = null;
isset($test->fake[‘doesNotExist’]->stilFake); // false
Whereas is_null would throw an error trying to walk a fake path. “isset” does essentially a try/catch-type thing around the check it’s doing.The value that empty() provides in PHP is similar to a null coalescing operator in many languages:
if (empty($foo->bar['baz'])) {
In this line of code all of the above can be missing. $foo can be an undefined variable, let alone one that has a value, and likewise all of the members, arrays, keys, etc. can also be missing. It does not throw an exception or trigger any warnings/errors to be logged, since, well, that's the purpose of empty.If you want similar-ish behavior but you're not interested in the problems associated with the empty semantics, use isset() as it has the same properties for non-existent keys.
An int with the value 0 isn't empty.
If an int with 0 is empty a string with a only white spaces is the same kind of empty.
I think empty mixes the computer meaning of empty with the linguistic meaning.
I'll answer - there really isn't one. You could say "undefined" but we already have another word for that ("undefined") - an "empty" construct doesn't exist in any other programming language that I'm aware of. Back in PHP's way-too-helpful days, they came up with this concept, so they got to define what it meant. (And to be fair, as with other things from the bad old days, it has caused confusion ever since.)
[1]: See the warning on this page, this applies to all languages with floating point arithmetic. https://www.php.net/manual/en/language.types.float.php
When working with things like money amounts, lengths, etc, store values as ints of the smallest denominator you support. For example, store $1.23 as 123 cents, or 4.567 meters as 4567 tenths of a centimeter. If you want to still allow the user to be able to, for example, enter a price as 1.23, multiply by 100 on input (like `$priceInCents = round($_POST['price'] * 100);`) and divide by 100 when displaying the value(`number_format($priceInCents / 100, 2)`), but keep it as an int all the way in between.
In terms of PHP, this also makes empty() a lot more predictable, because once a value is cast as int, the only time empty() will return true is if it is zero - or you could explicitly code `$priceInCents === 0` and have the exact same result.
Dynamic programming languages usually have some arbitrary rules about what X is treated true or false in
if(X) (…}
whatever rules are used are what you want almost always except for the times that they aren’t. A strongly typed language like Java will require X to be a boolean which now puts a load on the programmer to choose some f such that if(f(X)) {}
which could be correct every time in principle but a small increase in cognitive load is certain while most likely the f you choose (inclusive of your choice and it’s action) will do the right thing almost all the time except when it doesn’t. So I wouldn’t laugh at any particular programming language’s almost-right choice for ‘casting’ any to boolean because people are going to screw it up in any programming language.https://www.reddit.com/r/lolphp
Here the top posts of all time:
Otherwise more or less fine?
The whole OP here is a longwinded way of observing that several built-in PHP functions don't know anything about types. You can't use switch() as it's usually documented either, for example, because that ignores types too.
There are ways around all these things, of course. PHP that doesn't suck is kind of the norm these days. Just stay the hell away from Wordpress