开发者

defining an empty variable?

suppose

$test = '';

if(empty($test)){ $test = "not 开发者_如何学Cfound";}

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


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


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;


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

CORRECTED:

$test = trim($test);

if (empty($test)) ...

Trim removes whitespace from both sides of a string.


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))) {


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜