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

My Second Year on the WordPress Plugin Review Team

And yes, I've been contributing to WordPress in the Plugins team for two years now. For those who…

Cierre Ventana

State of the Word: Plugins

Photo taken by wordpress.org Yesterday, the new features that WordPress will be working on in the coming year…

Cierre Ventana

New version of Plugin Check Plugin 1.3.0

A new version of Plugin Check Plugin has been released. Version 1.3.0 brings enhancements, including new checks for…

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>