Quick PHP Tip

If you’re coding in PHP and checking variables to see if they have a strlen() == 0, or isset() or a variety of other possibilities, you might consider using empty() instead. It’s quite versatile and is nice because it doesn’t trigger any warnings or notices if you use it on a variable which hasn’t been set yet. Here are some examples to show you what it will match against:

<?php

$zero_string  = '0';
$zero_int     = 0;
$false        = false;
$empty_string = '';
$array        = array();
$obj          = new stdClass();

echo empty( $zero_string ) ? "'0' = empty\n" : '';
echo empty( $zero_int ) ? "0 = empty\n" : '';
echo empty( $false ) ? "false = empty\n" : '';
echo empty( $empty_string ) ? "'' = empty\n" : '';
echo empty( $array ) ? "array() = empty\n" : '';
echo empty( $obj ) ? "stdClass() = empty\n" : '';
echo empty( $foo ) ? "foo is empty (and the variable was never set)\n" : '';