In php 7 I did this.The output should be 0 right?But I am getting a 1.Why is that?
<?php
echo "a"==0?1:0;
?>
In php 7 I did this.The output should be 0 right?But I am getting a 1.Why is that?
<?php
echo "a"==0?1:0;
?>
"a" == 0 evaluates to true.
Because any string is converted into an integer when compared with an integer
. If PHP can't properly convert the string then it is evaluated as 0. So 0 is equal to 0, which equates as true.
If you want the answer as 0,
you should use === instead of ==,
Because the ordinary operator does not compare the types. Instead it will attempt to typecast the items.
Meanwhile the === takes in consideration type of items.
=== means "equals",
== means "eeeeh .. kinda looks like"
Also, the PHP manual for comparison http://au.php.net/manual/en/language.operators.comparison.php
// double equal will cast the values as needed followin quite complex rules
0 == '0' // true, because PHP casted both sides to numbers
// triple equals returns true only when type and value match
0 === '0' // false
FYI, From the PHP manual:
String conversion to numbers
When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.
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). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.