Re: Comparing non-empty string and 0 - is this behavior to be expected?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux