In PHP it’s fairly common to see the
We run across these all the time and can easily understand what happens when we pass them a
false value. However what happens when the condition of the
if statement is an object, a string, or a number?
What Is Truthy/Falsy?
Loosely typed languages like PHP allow us to use any kind of variable as if it was a boolean value in our
When PHP needs to evaluate the
if statement it converts our variable into something is can represent as a boolean. Ideally this would be a
false but in PHP it will convert any variable into something it can represent as one of those two values. This is where “truthy” and “falsy” come in. A variable that isn’t
false can be truthy or falsy.
Luckily for us there’s a logical consistency with how PHP type juggles our variables into truthy and falsy. For the most part the logic is that anything “empty” is falsy and anything with a value is truthy.
0 is falsy but
-1 are truthy.
Empty arrays are falsy but arrays with a value are truthy.
Empty strings are falsy but strings with a value are truthy.
null values are falsy.
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.