PHP If Checks

July 27, 2014

It’s really common in PHP to check a variables status with some code like this:


if($myVariable) {
    // run some code

If you’re a PHP developer, there’s a good chance you’ve done this hundreds of times, but do you know what it’s really doing?

Code inside an if-check like the one above is checking to see if the variable evaluates to any truthy value.

Here are some examples to help illustrate what’s it’s doing:


// Things that will FAIL the check

$myVariable = '';
if($myVariable) // false

$myVariable = 0;
if($myVariable) // false

$myVariable = NULL;
if($myVariable) // false

$myVariable = array();
if($myVariable) // false

// Things that will PASS the check

$myVariable = 'false';
if($myVariable) // true

$myVariable = 1;
if($myVariable) // true

$myVariable = 'Hello World';
if($myVariable) // true

$myVariable = array(1);
if($myVariable) // true

if($undefinedVariable) // Error

Behind the Scenes

If you’re ever unsure what something is going to evaluate to, you can just cast it as a boolean in PHP to see.

For example:

var_dump((bool) '');

// or

var_dump((bool) 'Hello World!');

Hope that helps!