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 secure

.

Return 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( $order['client_name'] ) && ! empty( $order['client_name'] ) )

    For an array we should also add the check if it's 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, it is customary 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 Comment

ÚLTIMOS ARTÍCULOS

Cierre Ventana

A great year on the WordPress plugin team

It’s been a great year for the WordPress Plugins Team. You can see the numbers in a summary…

Cierre Ventana

Develop more secure WordPress Plugins

Introduction Plugin Check Plugin is the new tool available to everyone that allows you to do automatic reviews…

Cierre Ventana

Create your own WordPress plugin, from scratch or already knowing some

Speakers: Francisco Torres, Paco Marchante and myself, David Pérez. We had the opportunity to be at WordCamp Madrid…

Logo David
Privacy Resume

Esta web utiliza cookies para que podamos ofrecerte la mejor experiencia de usuario posible. La información de las cookies se almacena en tu navegador y realiza funciones tales como reconocerte cuando vuelves a nuestra web o ayudar a nuestro equipo a comprender qué secciones de la web encuentras más interesantes y útiles.Para más información consulta nuestra <a href="/politica-privacidad/">Política de Privacidad</a>