3

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??

tereško
  • 58,060
  • 25
  • 98
  • 150
alwyn
  • 75
  • 1
  • 2
  • 6
  • 1
    A string is empty if its length is 0. A string with a single space character has the length 1. – Gumbo May 09 '11 at 17:27

5 Answers5

8

$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?

Community
  • 1
  • 1
Paul DelRe
  • 4,003
  • 1
  • 24
  • 26
6

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;
pickypg
  • 22,034
  • 5
  • 72
  • 84
1

You could do if (empty(trim($test))) ...

CORRECTED:

$test = trim($test);

if (empty($test)) ...

Trim removes whitespace from both sides of a string.

Austin
  • 475
  • 3
  • 8
  • -1 because `empty` only works on variables, not on expressions. This case is explicitly mentioned in the PHP manual that it will *not* work. – Sander Marechal May 09 '11 at 17:28
1

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))) {
mario
  • 144,265
  • 20
  • 237
  • 291
0

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.

Thilo
  • 17,565
  • 5
  • 68
  • 84