Check if variable is empty

Very important and handy thing to know. Elementary PHP stuff.

Here we’ll use the empty().


if (empty($args)) {
  //do something if empty
} else {
 //do something else if not empty
}

But that’s kinda long way to do it. Many times it’s more handy to ask if it’s not empty.


//note the exclamation mark
if (!empty($args)) { /*do something here*/ }

Much more compact.

Real world example from WordPress

Get some author profile fields. In this case, it’s important to check if the variables have content in them, or otherwise leave empty elements into the code (or the “Tel:” would be there for nothing).


$author_id = 2;
$address   = get_the_author_meta('address', $author_id );
$phone     = get_the_author_meta('phone', $author_id );
$fax       = get_the_author_meta('fax', $author_id );

if (!empty($phone)) {echo '
' . wpautop($address) . '
';} if (!empty($phone)) {echo 'Tel: ' . $phone;} if (!empty($fax)) {echo '
Fax: ' . $fax;}

Check if the_content() has something in it

In PHP the == means is equal to.


post_content == "" ) : //is equal to nothing
    //Do something if empty
  else :
    //Do something if not empty
  endif;
?>

Real world example could be something like:

Display the “Read More →” buttom only if the post content has something in it. It may be that only the excerpt has content and therefore, there is no need for the read more link.


post_content == "" ) :
    //nada
  else :
?>
  Keep Reading →

Comments

Club-Mate, the beverage → club-mate.fi