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.

Deja un comentario

ÚLTIMOS ARTÍCULOS

Cierre Ventana

Analiza tu código automáticamente con PHPSTAN

En proyectos de WordPress, mantener un código limpio y libre de errores es fundamental para garantizar la calidad,…

Cierre Ventana

Desarrolla y crea Test para que tus plugins no tengan errores

Este es el tutorial que vamos a tener en cuenta para la charla de la WordCamp Galicia 2025.…

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…

Este sitio está registrado en wpml.org como sitio de desarrollo. Cambia a una clave de sitio de producción en remove this banner.