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:


$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" : '';
  1. Sometimes I find that even though php is loosely typed, I would much rather keep track of what type my variables are in an application. I think using empty may confuse the issue and create harder to follow code if you use it every place against different types. isset() followed by a comparison of == '0' or == 0 not only does the same thing, but also informs the reader what type I'm expecting the variable to contain.

  2. Beau Lebens said:

    1. If you're going to do that, a nice trick from WP coding style is to always do 0 == $var or '0' == $var to avoid accidental assignment (if you miss a = it'll throw a syntax error),
    2. I'd rather use is_int() or whatever if you're that concerned about specific types,
    3. Doing the isset() and then another comparison means you're doubling the amount of operations you're doing, just to test if something's around and available

    • Donncha said:

      Just watch out if the numbers are bigger than PHP's INT can cope with. My Tweet Tweet plugin used intval() to cast the Twitter ID but it passed the magic 32 bit limit 256k tweets back. Deleted all of them and replaces with $wpdb->escape()

      'Fraid I fall into the isset() and compare camp, or maybe I've just never experimented much with empty()

      • Beau Lebens said:

        That's a very good point RE: the size of ints. Probably not *tooooo* many situations where we'll run up against that, but definitely something to keep in mind (and probably best set as a habit rather than relying on being able to guess when it's going to happen!).

        isset() and compare is definitely useful, it just applies to a (potentially) different situation (or rather, empty() applies to a specific subset of the same situations as isset() and compare, where you're specifically looking for an empty/will-evaluate-as-false condition). If I'm looking for a specific value or a range of values or something, then I'll use isset() or !empty() and then compare. I wonder if there's any performance difference between the 2? Might have to check that 🙂

Comments are closed.