15 1 0 4000 1 https://codeblock.co.za 300 true 0
theme-sticky-logo-alt

empty()

0 Comments

Programming Language

PHP [Versions: 4, 5, 7, 8]

Syntax

Typical Usage

Checks a variable to determine whether or not it contains something.

Accepted Parameters

  • variable (mixed) (Required): The variable you wish to check.

Return Value(s)

Returns false if the variable exists and has a non-empty, non-zero or true value. Otherwise returns true.

Notes

No warning is generated if the variable has not been declared, so empty() can be used instead of  !isset($variable) or $variable == false.

Examples

Example 1

<?php
$heroes = [
    [
        'name' => 'Plunder Woman',
        'element'=> '',
    ],

    [
        'name' => 'Mister Blister',
        'element'=> 'Fire',
    ],

    [
        'name' => 'Bow Cross',
        'element'=> 'Earth',
    ],

];

foreach($heroes as $hero) {
    if( empty($hero['element']) ) {
        $hero['element'] = 'Ether';
    }

    echo $hero['name'] . ' - ' . $hero['element'] . '<br>';
}

In the above example, by using empty() in a conditional, a fallback element can be ensured in the case that a hero is not assigned an element. The output would be:

Blunder Woman - Ether
Mister Blister - Fire
Bow Cross - Earth

Was This Helpful?

Previous Post
array_combine()
Next Post
in_array()

0 Comments

Leave a Reply