empty()
21st January 2021
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
Used In Projects
Was This Helpful?
If this post has helped you, please let me know. Your feedback will be highly appreciated and will help me build better content.