4

I am retrieving some data from an in-house store and in case of failure, I get a very specific response. Calling strlen() on this variable returns the value of zero. It is also not equal to NULL or "". I'm using this code to test:

if ($data === NULL)
{
    echo("data was null\n");
}
else if ($data === "")
{
    echo("data was empty string\n");
}
else if (strlen($data) == 0)
{
    echo("data was length zero\n");
}

This result is outputting data was length zero. What could the variable contain that is zero length, not null, and not the empty string?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98

3 Answers3

2

Returned value must be false then.

 echo strlen(false); // outputs 0 
Orangepill
  • 24,500
  • 3
  • 42
  • 63
1

This may not being an answer. I can only answer if you present a var_dump($data); But I think also suprising for me is this:

$data = "\0";

if ($data === NULL)
{
    echo("data was null\n");
}
else if ($data === "")
{
    echo "data was empty string\n";
}
else if (strlen($data) == 0)
{
    echo "data was length zero\n";
} 
else 
{
    echo "something strange happened\n";
}

Output: something strange happened

:)

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • An ASCII NULL character in a string is not the same as a [NULL datatype](http://www.php.net/manual/en/language.types.null.php). – Mark Baker Jul 11 '13 at 22:21
  • 1
    **Beauty of PHP's binary strings.** `\0` has `strlen()` of 1... *EPIC!* PHP does not have strings but byte arrays. You can stick anything in them and `\0` has no effect on it :) `strlen` is more like `count`. – CodeAngry Jul 11 '13 at 22:21
  • @MarkBaker I know that but I expected a strlen of zero. Thx CodeAngry!!! Of course you are right, we are not in C!! sorry I was totally wrong.... will delete the post as soon as you both read my comment – hek2mgl Jul 11 '13 at 22:23
  • 1
    @hek2mgl You could leave it here so others can read my comment in case they come from a C/C++ background like me :) I very much hate dynamic typed languages where anything is anything else. – CodeAngry Jul 11 '13 at 22:26
  • @CodeAngry About dynamically typed languages. I don't hate them but I'm with you, loose typing makes more problems than it brings benefits – hek2mgl Jul 12 '13 at 08:38
0

Try this :

    $data = false;

I'm not sure why false has a strlen, but it does.

Dany Caissy
  • 3,176
  • 15
  • 21
  • $data = 0; Does not give the same result, though. – Dany Caissy Jul 11 '13 at 22:23
  • It has a `strlen` for the same reason that you can add two strings (`"aa" + "bb"`) or that you can `str_replace(0, null, false)`: values are automatically converted to whatever type their consumer wants. It's another matter that the result might not be meaningful. – Jon Jul 11 '13 at 22:24