40

I've seen a lot of php code that does the following to check whether a string is valid by doing:

$str is a string variable.

if (!isset($str) || $str !== '') {
  // do something
}

I prefer to just do

if (strlen($str) > 0) {
  // something
}

Is there any thing that can go wrong with the second method? Are there any casting issues I should be aware of?

Yada
  • 30,349
  • 24
  • 103
  • 144

9 Answers9

49

Since PHP will treat a string containing a zero ('0') as empty, it makes the empty() function an unsuitable solution.

Instead, test that the variable is explicitly not equal to an empty string:

$stringvar !== ''

As the OP and Gras Double and others have shown, the variable should also be checked for initialization to avoid a warning or error (depending on settings):

isset($stringvar)

This results in the more acceptable:

if (isset($stringvar) && $stringvar !== '') {
}

PHP has a lot of bad conventions. I originally answered this (over 9 years ago) using the empty() function, as seen below. I've long since abandoned PHP, but since this answer attracts downvotes and comments every few years, I've updated it. Should the OP wish to change the accepted answer, please do so.

Original Answer:

if(empty($stringvar))
{
    // do something
}

You could also add trim() to eliminate whitespace if that is to be considered.

Edit:

Note that for a string like '0', this will return true, while strlen() will not.

Community
  • 1
  • 1
JYelton
  • 35,664
  • 27
  • 132
  • 191
  • is there any different between if(empty(trim($str))) and if (strlen(trim($strim))> 0) ? – Yada Dec 25 '10 at 21:14
  • 17
    Yes. Consider the string `'0'` on which `empty()` will return true while `strlen()` will not. – JYelton Dec 25 '10 at 22:00
  • Also see: http://stackoverflow.com/questions/1318350/is-there-any-difference-between-strlenvar-0-and-emptyvar – JYelton Dec 25 '10 at 22:04
  • 12
    This is worse than `strlen( $str ) > 0` because it considers `"0"` to be an empty string. – Jesse Jun 17 '13 at 03:43
  • "Worse" depends on the OP's requirement. If "0" should be treated as *not* empty, then this method is not ideal. It is just an alternate suggestion. However, in many situations, "0" might just as well be empty. It's situational. – JYelton Jun 17 '13 at 06:12
  • 6
    I wouldn't suggest this method because a string value of `"0"` is considered empty. – Jake Wilson Mar 21 '14 at 17:25
  • As explained by Jesse, this answer is WRONG! – Marco Demaio Apr 01 '16 at 10:32
  • This will fail if you validate the string '0'. A string with the zero digit will be assumed empty. – jpruiz114 Nov 26 '17 at 19:33
  • @JeanPaulRuiz Yes. It's been mentioned (repeatedly) in previous comments as well as an addendum in the answer. – JYelton Nov 26 '17 at 19:34
  • 1
    @ToolmakerSteve I've edited this (again) to hopefully avoid having any newcomers stumble upon the horrific mistakes made 9+ years ago. – JYelton Jul 01 '19 at 23:23
16

You need isset() in case $str is possibly undefined:

if (isset($str) && $str !== '') {
    // variable set, not empty string
}

Using !empty() would have an important caveat: the string '0' evaluates to false.


Also, sometimes one wants to check, in addition, that $str is not something falsy, like false or null[1]. The previous code doesn't handle this. It's one of the rare situations where loose comparison may be useful:

if (isset($str) && $str != '') {
    // variable set, not empty string, not falsy
}

The above method is interesting as it remains concise and doesn't filter out '0'. But make sure to document your code if you use it.

Otherwise you can use this equivalent but more verbose version:

if (isset($str) && (string) $str !== '') {
    // variable set, not empty string, not falsy
}


Of course, if you are sure $str is defined, you can omit the isset($str) from the above codes.


Finally, considering that '' == false, '0' == false, but '' != '0', you may have guessed it: PHP comparisons aren't transitive (fun graphs included).


[1] Note that isset() already filters out null.

Gras Double
  • 15,901
  • 8
  • 56
  • 54
10

This will safely check for a string containing only whitespace:

// Determines if the supplied string is an empty string.                                                                                 
// Empty is defined as null or containing only whitespace.                                                                               
// '0' is NOT an empty string!                                                                                                           
function isEmptyString($str) {
  return !(isset($str) && (strlen(trim($str)) > 0));
}
Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
3

What about this:

if( !isset($str[0]) )
   echo "str is NULL or an empty string";

I found it on PHP manual in a comment by Antone Roundy

I posted it here, because I did some tests and it seems to work well, but I'm wondering if there is some side effect I'm not considering. Any suggestions in comments here would be appreciated.

Gras Double
  • 15,901
  • 8
  • 56
  • 54
Marco Demaio
  • 33,578
  • 33
  • 128
  • 159
  • Note this method also supports `'0'`, `false`, `null` (gives respectively true, false, false) as in the loose comparison `== ''` stuff in my answer. – Gras Double Mar 31 '16 at 21:53
  • @GrasDouble: yep, you are right. The problem would be ehn string is '0' – Marco Demaio Apr 01 '16 at 10:37
  • There was a misunderstanding. I meant your code considers `'0'` to be a non-empty string, just like any other string. So it's working fine actually :) – Gras Double Jun 12 '20 at 21:41
2

According to PHP empty() doc (http://ca1.php.net/empty):

Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

Instead, use trim($name) == false.

2

This simple old question is still tricky.

strlen($var) works perfectly ONLY if you're absolutely sure the $var is a string.

isset($var) and empty($var) result are based on type of the variable, and could be tricky at some cases (like empty string ""). View the table in this page for more details.

UPDATE

There are actually 2 cases for this question:

Case 1: You're sure that your variable is always going to be a "string":

In this case, just test the length:

if(strlen($str) > 0) {
    // do something..
}

Case 2: Your variable may and may not be a "string":

In this case, it depends on what you want to do. For me (most of the time), if it's not a string then I validate it as "false". You can do it this way:

if(is_string($var) && $var !== '') {// true only if it's a string AND is not empty
    // do something ...
}

And to make it shorter and in 1 condition instead of 2 (specially useful if you're testing more than 1 string in same if condition), I made it into function:

function isNonEmptyString($var) {
    return is_string($var) && $var !== '';
}


// Somewhere else..
// Reducing conditions to half
if(isNonEmptyString($var1) && isNonEmptyString($var2) && isNonEmptyString($var3)) {
    // do something
}
evilReiko
  • 19,501
  • 24
  • 86
  • 102
1

If your variable $str is not defined then your strlen() method will throw an exception. That is the whole purpose of using isset() first.

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
0

trimming the string will also help if there are string with white spaces.

if (isset($str) &&  trim($str) !== '') {
    // code
}

-3

I think not, because strlen (string lenght) returns the lenght (integer) of your $str variable. So if the variable is empty i would return 0. Is 0 greater then 0. Don't think so. But i think the first method might be a little more safer. Because it checks if the variable is init, and if its not empty.

Sebastjan
  • 1,117
  • 2
  • 17
  • 24