php

Why does this false value convert to empty string instead of 0?


After a data-base query requested via a POST, I send a JSON-encoded response back to caller (browser or app).

php:

$result = Database::query($str_query);

$emailAvailable = $result->num_rows < 1;
echo("200 OK\r\n" . '{"available": "' . $emailAvailable . '", "query": "' . $str_query . '", "count": "' . $result->num_rows . '"}');

echoed string:

200 OK
{"available": "", "query": "SELECT * FROM tblusers WHERE email='test@test.com'", "count": "1"}

What I expected to get back was "0" for the value of "available", instead of "":

200 OK
{"available": "0", ...

As you can see, the query returned a row count of 1. So I expected $emailAvailable to contain a boolean false (1 < 1).

I was able to fix, by explicitly forcing the value to be "1" or "0" by replacing

. $emailAvailable .

with:

. ($emailAvailable ? "1" : "0") .

But I'd like to understand why this was necessary.

Would

. boolval($emailAvailable) .

have been an alternative "fix"? (though I'd still like to know why)


Solution

  • You can read the manual here: http://php.net/manual/en/language.types.string.php#language.types.string.casting

    A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

    If you want to cast your variable to an integer, just use the (int) caster.

    echo("200 OK\r\n" . '{"available"="' . (int) $emailAvailable . '", "...