A good[ish] website

Web development blog, loads of UI and JavaScript topics

Check if variable is empty in PHP

Filed under: WordPress/PHP— Tagged with: php

Part of the PHP basics series.

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 '<address>' . wpautop($address) . '</address>';

if (!empty($phone)) {
  echo 'Tel: ' . $phone;

if (!empty($fax)) {
  echo 'Fax: ' . $fax;

Check if the_content() has something in it

Use the equals to operator ==:

// Is equal to nothing
if ( $post->post_content == "" ) :
  // Do something if empty
else :
  // Do something if not empty

Real world example

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

  if ($post->post_content == "") :
    // Nothing
  else :
  [" class="more-link">Keep Reading &rarr;](<?php the_permalink(); ?)
<?php endif; ?>

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!