What is the difference between using empty() and !empty() in PHP to check if a variable is empty?
The difference between using empty() and !empty() in PHP to check if a variable is empty lies in the return values. The empty() function returns true if a variable is empty (or evaluates to false), while !empty() returns true if a variable is not empty (or evaluates to true). Therefore, empty() is used to check if a variable is empty, and !empty() is used to check if a variable is not empty.
// Using empty() to check if a variable is empty
$var = '';
if (empty($var)) {
echo 'Variable is empty';
} else {
echo 'Variable is not empty';
}
// Using !empty() to check if a variable is not empty
$var = 'Hello';
if (!empty($var)) {
echo 'Variable is not empty';
} else {
echo 'Variable is empty';
}
Related questions
-
user input validation PHP scripts spaces
-
dynamic arrays memory management array functions
-
PHP error unexpected T_VARIABLE