Re: Comparing non-empty string and 0 - is this behavior to be expected?
| From: | Christoph M. Becker | Date: | Sun, 05 Apr 2020 09:44:19 +0000 |
| Subject: | Re: Comparing non-empty string and 0 - is this behavior to be expected? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-327091@lists.php.net to get a copy of this message | ||
On 05.04.2020 at 08:38, Jeremy O'Connor wrote:
> Looking at the following code
>
> echo ('') ? 'T' : 'F';
> echo ('!') ? 'T' : 'F';
> echo (0) ? 'T' : 'F';
> echo ('' == 0) ? 'T' : 'F';
> echo ('!' == 0) ? 'T' : 'F';
>
> the output is:
>
> FTFTT
>
> Is this behavior to be expected?
Yes, it is. From the PHP manual[1]:
| If you compare a number with a string or the comparison involves
| numerical strings, then each string is converted to a number and the
| comparison performed numerically.
and from the string conversion to numbers section[2]:
| The value is given by the initial portion of the string. If the string
| starts with valid numeric data, this will be the value used.
| Otherwise, the value will be 0 (zero).
You can avoid this behavior by using the identity operator (===).
[1] <https://www.php.net/manual/en/language.operators.comparison.php>
[2]
<https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion>
--
Christoph M. Becker