Reputation: 75
suppose
$test = '';
if(empty($test)){ $test = "not found";}
echo $test;
the above case the answer will be "not found"
but below one even though the $test
variable is empty but result give nothing.
$test = ' ';
if(empty($test)){ $test = "not found";}
echo $test;
how we can treat both these variables as empty in PHP??
Upvotes: 3
Views: 14735
Reputation: 145512
I have no idea why everybody is recommending empty
here. Then you could just leave it out and use PHPs boolean context handling:
if (!trim($test)) {
But to actually check if there is any string content use:
if (!strlen(trim($test))) {
Upvotes: 1
Reputation: 475
You could do if (empty(trim($test))) ...
CORRECTED:
$test = trim($test);
if (empty($test)) ...
Trim removes whitespace from both sides of a string.
Upvotes: 1
Reputation: 4039
$test = ' '
is not empty. From the details in the documentation:
The following things are considered to be 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 $var; (a variable declared, but without a value in a class)
If you want to test if $test
is only white space characters, see these questions:
If string only contains spaces?
How to check if there are only spaces in string in PHP?
Upvotes: 8
Reputation: 17735
Create your own function to test this:
function my_empty($str) {
$str = trim($str);
return empty($str);
}
That will treat all strings containing only whitespace as empty, in addition to whatever the empty method already provides.
Upvotes: 0
Reputation: 22332
Trim the value before checking it.
It is important to trim before checking it because empty
only checks variables and not the value you're passing in.
$test = trim(' ');
if (empty($test)) { /* ... */ }
echo $test;
Upvotes: 6