Skip to Content
Learn
Booleans and Comparison Operators
Truthy and Falsy

So far in our conditionals, we’ve been dealing with expressions that would evaluate to boolean values in any context. In practice, any value or expression in the condition will be converted to TRUE or FALSE. Take a look at the following real, working PHP code:

if ("What's going on?"){ echo "Let us explain…"; } // Prints: Let us explain…

In the above code, the condition checks the truthiness of the string "What's going on?". The computer converts this value to TRUE and therefore executes the code in the block. We sometimes refer to code that will be converted to TRUE as truthy and code that will be converted to FALSE as falsy since they aren’t actually equivalent to those boolean values, but they will be treated as such in certain contexts. Most values and expressions are treated as truthy, so we’ll focus on those that are falsy:

  • Empty strings
  • null
  • an undefined or undeclared variable
  • an empty array
  • the number 0
  • the string "0"

Let’s see this in action:

if ("") { echo "this will not print"; } elseif (null) { echo "this will not print"; } elseif ([]) { echo "this will not print"; } elseif (0) { echo "this will not print"; } elseif ("0") { echo "this will not print"; } else { echo "Finally!"; }

Since none of the conditions above hold truthy values, the code will print Finally!.

This can be tricky, so let’s get some practice with it.

Instructions

1.

Since it’s hard to keep track of what’s truthy or falsy in PHP, let’s write a function to check for us! Write a function truthyOrFalsy() that takes in any value and returns the string "True" if that value is truthy and the string "False" if that value is falsy.

2.

Test your function! Invoke your function at least once with a truthy value and at least once with a falsy value. Be sure to use echo to print the results to the terminal.

Folder Icon

Take this course for free

Already have an account?