On 2020/04/05 11:44, Christoph M. Becker wrote:
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
Thanks Christoph for your answer. What is happening after reading the
links you posted is:
1. echo ('!') ? 'T' : 'F'; // T
2. echo ('!' == 0) ? 'T' : 'F'; // T
In 1., the string '!' is being converted into a bool, which will be TRUE.
In 2., the string '!' is being converted into an integer, which will be
0, which will equal the RHS of the == operator, and the expression will
return TRUE, as expected.
So, it seems that depending on the context a string may be type-juggled
to a bool or an integer.
Perhaps a string should always be type-juggled to a similar semantic
value, like:
For string -> bool type-juggling:
"" empty string is converted to FALSE.
non-empty string is always converted to TRUE (even when it consists only
of the character '0' i.e "0").
For string -> integer type-juggling:
Perhaps instead of:
"" empty string is converted to 0.
non-empty string is converted to 0 (when it does not start with an
integer N).
non-empty string is converted to N (when it starts with an integer N).
we should have:
"" empty string is converted to 0.
non-empty string is converted to 1 (whether or not it starts with an
integer N).
I know this will most likely break so much existing code that it's
probably not a realistic option right now.
--
Jeremy O'Connor