Warning: Constant SAVEQUERIES already defined in /var/www/vhosts/davidperezgar.com/httpdocs/wp-config.php on line 41
Best practices in web development: use of empty – Davidperezgar.com
Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /var/www/vhosts/davidperezgar.com/httpdocs/wp-content/plugins/wpautotranslate-pro-mlp/public/class-wpautotranslate-public.php on line 95

Best practices in web development: use of empty



The empty() function in PHP is used to check if a variable exists and if its value is considered empty. It’s a good practice to make your code not break when you receive variable values that you have to ensure

Returns true if the variable does not exist or if its value is one of the following:

  • “” (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • “0” (0 as a string)
  • null
  • false
  • array() (an empty array)

Since empty checks that the variable exists, it would save us this statement:

if ( isset( $order['client_name'] ) && '' != $order['client_name'] )

To this one which is much more abbreviated:

if ( ! empty( $order['client_name'] )
if ( isset( $order['client_name'] ) && ! empty( $order['client_name'] ) )

For an array we should also add the check if it is an array:

if ( ! empty( $order ) && is_array( $order ) )

And you could also use it in a ternary:

$client_name = ! empty( $order['client_name'] ) ? $order['client_name'] : '';

But in these cases, the usual is to use isset:

$client_name = isset( $order['client_name'] ) ? $order['client_name'] : '';

The empty() function is commonly used in control flow structures, such as if and while, to check if a variable has a valid value before performing an action or making a decision based on that value. It can also be used in web forms to check whether or not a field has been filled in before processing the data submitted by the user.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.