Why is integer 0 equal to a string in PHP? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?
Why this
var_dump(0 == "string");
outputs this
bool(true)
Isn't the context of == operator supposed to convert 0 into FALSE and "string" into TRUE according to this set of rules?

var_dump(0 == "string");
is doing a numeric (integer) comparison
0 is an integer, so "string" is converted to an integer to do the comparison, and equates to an integer value of 0, so 0 == 0 is true
Se the comparison with various types table in the PHP documentation for details

The table shown here is more fit for your case.
It shows TRUE for comparing 0 with "php".
Within the comparison you do not convert both operands to a boolean, but one operand will be converted to match the type of the other operand. In your case the string gets converted to an integer, which results in another 0. This gives you 0 == 0, which yields true.

They are not of the same type, use === if you want to check if they are also of the same type.

PHP: ==
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.
"string" is not number format, so it will be convert to 0.

during the comparison, the string is converted to an integer:
var_dump(0);
var_dump((int)"string");
var_dump(0 == "string");
last line will be automatically converted to:
var_dump(0 == (int)"string");
so this return will return:
int(0)
int(0)
bool(true)
bool(true)

You're looking for the comparison table on this site first: http://php.net/manual/en/language.operators.comparison.php. Casting to bool doesn't apply here.
Operand 1 Operand 2
...
string, resource string, resource Translate strings and resources to numbers,
or number or number usual math
"string" cast to a number equals 0.

Related

php why does 0 == 'somestr' evaluate to true [duplicate]

This question already has answers here:
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Why does PHP consider 0 to be equal to a string?
(9 answers)
Closed 4 years ago.
I have this code:
echo ( $arr['process_refunds'] == 'storecredit' ) ? 'true' : 'false'
The value in $arr['process_refunds'] is 0 type int(0).
It tried in php -a and it turns out that if we compare any string with
== with int(0) it evaluates to true.
Why is that?
This is because == is a loosely-typed comparison operator. It is converting your string to a number, therefore it evaluates to true. Try using ===.
Your string is getting converted to a zero because it starts with a letter.
I think it's pretty obvious that the loose comparison is not returning expected values. You can see the comparison table here (2nd table)
http://php.net/manual/en/types.comparisons.php
you can see that this is expected behaviour. This is because php converts the string "php" or "somestr"to a match the number type, making it equal to 0, before making the assessment.
Unless there are other types/conditions you're looking to match with a loose comparison, to get around this, you should use === that will assure you have the matching type.
Firstly:
php -r "echo ( $arr['process_refunds'] == 'storecredit' ) ? 'true' : 'false';"
prints:
false
It is obvious because $arr is undefined. But if it has value 0 then
php -r "echo ( 0 == 'storecredit' ) ? 'true' : 'false';"
prints:
true
because both 0 and 'storecredit' are converted to integers.
Value of (int) 'storecredit' is 0 because of it does not contain any number on start of string. For example string '4ss' would be converted to 4.
You need no use === because in that way you compare both values are the same type and the same content; example
echo 0 === 'somstr'; // returns false
echo 0 == 'somstr'; //return true

Why (false==0) is TRUE? [duplicate]

This question already has answers here:
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 6 years ago.
I just var_dump(false==0) it outputs bool(true) Why false== 0 is true.I know true==1 is true Because if i echo true; It will output 1 so numeric value of true is 1, But numeric value of false is not 0, because when i echo false; It display nothing(empty), So how can false has same value as 0 AS we know == operator compares the values , if they same it will return true, and if their values is not same it will return false , so in the case of false==0 It should be false. Any idea ?
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.
So both false == "" and false == 0 are true. Remember, "0" is not the same as 0.
You can have a check here.
PHP Type Comparison
In short, == is the loose comparison operator which invokes type conversion before comparison. Maybe you should use the strict comparison operator === instead.
The same story goes in JavaScript.
false has the the same value as 0, it is just another way of writing it
So, false == 0 will be the same thing as saying
0 == 0
which returns true because 0 = 0

PHP compare equality, empty string, "0" and 0

I learned that the empty string "", 0 and "0" all mean false in php. I wonder does php take that into account when it comes to comparing equality.
$str = "";
echo ($str == "0") ? "yes" : "no"; // prints "no" (A)
echo ($str == 0) ? "yes" : "no"; // prints "yes" (B)
Line A suggests that php is comparing $str and "0" as if they are all strings, ignoring that they both can mean false. But line B is comparing their "false" interpretation.
So is it the case that php firstly checks if the two values have the same type, if so it checks equality assuming the same type; if not, it uses the boolean meanings of the values (is there type casting involved?)
I learned that the empty string "", 0 and "0" all mean false in php.
This statement is false. Empty string, 0 and "0" are false when casted to boolean type. Otherwise they are either empty string, integer zero or string with one character, respectively.
== checks values of two variables. If their types are different, some casting happens and unpredictable (for rookies) results come up.
=== checks values of two variables and their types.
Anyway, when you compare "0" == "", PHP interpreter compares two strings which are different. But when you go with 0 == "" it first changes numeric string to integer. Empty string equals 0. So we end up with 0 == 0 which is true.
Note: "8abc" becomes 8 after casting to integer. abc8 becomes 0 when casted
Manual on:
- Types casting (juggling)
- Types comparison
There are two equality comparator in PHP
When the types are the same, they behave in the same way.
When the types are different, it all depends: PHP does not cast both values to booleans. It depends on the types of both operands, and there is a table to know what PHP will do (see second link).
I recommend reading this stackoverflow question
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
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
$str = "";
//Comparing two strings, no implicit type conversion happens. Since
// "" is not equal "0", result is FALSE
echo ($str == "0") ? "yes" : "no"; // prints "no" (A)
//Comparing a STRING to an INT,implicit conversion happens to convert
// the string "" to an INT. Since "" has no digits, it's evaluated
// to 0. Hence, result of comparison is TRUE
echo ($str == 0) ? "yes" : "no"; // prints "yes" (B)
Use "===" for more accurate comparison.

Comparing int to string causes weird results in php? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
comparing two variables returns false result
<?php
if( "32 is this a bug of php " == 32)
echo "true";
else
echo "false";
?>
output is :
true
you can see its output at
http://codepad.org/hgOisqZ8
why this condition is evaluated as true?
because PHP is quite dumb when it comes to type conversion.
This expression is evaluated by first casting "32 is this a bug of php " to integer, which results with 32. Then comparison results in true.
If you want to make type-safe comparison use === operator
<?php
if( "32 is this a bug of php " === 32)
echo "true";
else
echo "false";
?>
Output will be false.
Note that with === operator we've got "32" !== 32 because one variable is string when other is int
This is discussed in 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.
Note the part that states
If the string starts with valid numeric data, this will be the value
used.
Since your string starts with 32 PHP will compare if(32 == 32) which will be true.
Use type safe checks, that takes the datatype into consideration, when dealing with types that could be different if this behaviour is not desired. Like
1 === 1: true
1 == 1: true
1 === "1": false
1 == "1": true
"foo" === "foo": true
See the documentation for comparison operators:
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.
So no, it isn't a bug, it is how the language is designed.
Use === if you don't want type juggling.
For attention, also you need to know $a==$b && $b==$c doesn't mean $a == $c in php.
Example:
var_dump('32E0' == '32');
var_dump('32' == 32);
var_dump(32 == '32 is a bug');
var_dump('32E0' == '32 is a bug');
Output is:
bool(true)
bool(true)
bool(true)
bool(false)
you can also use like this
<?php
if( "32 is this a bug of php " == '32')
echo "true";
else
echo "false";
?>

Comparison Operator - Type Juggling and Booleans

I've been reading the PHP Docs on Type Juggling and Booleans but I still don't understand why this comparison evaluates as true. My [incorrect] understanding tells me that in the below if statement, the integer 0 is considered FALSE and "a", being a non-empty string is considered TRUE. Therefore, I expected this comparison to resolve to FALSE == TRUE and ultimately, FALSE. Which part did I get wrong?
<?php
if(0 == "a"){
$result = "TRUE";
}else{
$result = "FALSE";
}
//$result == "TRUE"
?>
http://codepad.viper-7.com/EjxBF5
When PHP does a string <=> integer comparison, it attempts to convert the string to a number in an intelligent way. The assumption is that if you have a string "42" then you want to compare the value 42 to the other integer. When the string doesn't start with numbers, then its value is zero.
From the docs:
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).
This behavior is also inferred in the comparison docs (look at the first line in the first example).
Your mistake is that you assume operator == coerces each of its operands to boolean before comparing them. It does no such thing.
What happens is that since you are comparing an integer to a string, the string is converted to an integer (in this case "a" converts to 0) and then the comparison 0 == 0 is performed.
It will work if you use a strict comparison === instead of ==. The strict comparison also checks the type of the variables, so 0 === 'a' would be false.

Categories