I am checking a value to see if it is empty using the empty()
function in PHP. This validates the following as empty:
"" (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)
$var; (a variable declared, but without a value)
The value I am passing can be a string, array or number. However if a string has a space (" "
) it is not considered empty. What is the easiest way to check this condition as well without creating my own function? I cannot just do an empty(trim($value))
since $value
can be an array
.
EDIT: I am not trying to ask how to check if a string is empty. I already know that. I am asking if there is a way that I can pass an array, number or string to empty() and it will return the correct validation even if the string passed has empty spaces in them.
The best way is to create your own function, but if you really have a reason not to do it you can use something like this:
$original_string_or_array = array(); // The variable that you want to check
$trimed_string_or_array = is_array($original_string_or_array) ? $original_string_or_array : trim($original_string_or_array);
if(empty($trimed_string_or_array)) {
echo 'The variable is empty';
} else {
echo 'The variable is NOT empty';
}