Comment by nasretdinov
1 day ago
if("0") {} being equivalent to if(false) {} still gives me nightmares even though I've stopped using PHP for at least 6 years now :)
1 day ago
if("0") {} being equivalent to if(false) {} still gives me nightmares even though I've stopped using PHP for at least 6 years now :)
I knew this in and out, but as a Full-Stack PHP/Symfony/Frontend/JS guy who pivoted to mainly TS for b2b stuff, I still have to occasionally enter
into the browser console just to be sure, during code reviews :D
In JS/TS:
In PHP:
Honestly the only way to remain sane in either, but especially if you use both, is to always use === and never use boolean logic (!) when a string could be involved.
That's what I say in code reviews as well. Same for numbers.
!someValue is useful only for:
- booleans, including optional booleans (which is why every bool flag should default to false)
- undefined, null (falsy), or object/function (truthy)
It's nice for the second variant to also cover falsy NaN or things like this, for example for forms.
I guess that's where
comes from.
But it's this exact case that keeps tripping me up.
What about empty arrays?
Per my original comment, now I'd have to look up if
is false in PHP, or just empty([]) === true
.
So yea I agree, and extend your case to PHP "arrays" (in JS,
is
1 reply →
Also `empty("0") === true` is a common gotcha.
In what context are you doing if("0")? People always have these obscure type comparison complaints, not just for PHP, and all I can think is why would you write that?
Something you'll see in real codebases is code that cares whether an input value is "empty", but it doesn't matter if it's null or an empty string. It's very easy to go for this:
It'll work through every test case you try, and then someone enters a 0 into the field and it's also unexpectedly considered empty.