Comparing 2 different values returns true [duplicate] - php

This question already has answers here:
Why does (0 == 'Hello') return true in PHP?
(5 answers)
Closed 8 years ago.
I came across this while playing with php
$test1 = '123abc';
$test2 = 123;
var_dump($test1); echo "<br />";
var_dump($test2); echo "<br />";
$test3 = ($test1 == $test2) ? True : False;
var_dump($test3);
This resulted in:
string(6) "123abc"
int(123)
bool(true)
Could someone explain why $test3 came out true?
using "===" would make that false but that would be due to comparing string to int.
Also notice if I force (string)$test2 it would give me the expected false, and forcing (int)$test1 returns the expected true;
Does this mean $test3 return true because PHP automatically converted $test1 into int before comparison?

Look at the details here:
a string' == 0 also 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.
Also, in the official PHP documentation:
To explicitly convert a value to integer, use either the (int) or
(integer) casts. However, in most cases the cast is not needed, since
a value will be automatically converted if an operator, function or
control structure requires an integer argument.

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

my List of comparison operators in php returns '1' when I use keyword echo why

I'm begenning at PHP , I was poking around my code and learning about List of comparison operators , however I'll try out to put echo before my comparasion operators and I've received this result : 1 then I though the reason is comparasion true equal to 1, else equal to 0 , in this moment seemed me somethig kinda python, yet I just got the 1 . why not 0 as result ?
Is attached my question
You're printing a boolean value. The value is converted to a string where 1 represents true and a blank string represents false.
From the manual:
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.
http://php.net/manual/en/language.types.string.php
You could use the ternary operator to output the string true or false where appropriate. Example:
echo (10 >= 12) ? 'true' : 'false';
when print boolean value in php it will print 1 if TRUE and "" if FALSE.
if you want to print 0 if FALSE then you can convert into int.
in your case you can use like this
$bool = 10 >= 12;
echo (int)$bool;
it will return 0.
<?php
echo 10>=9 // print 1 as it is true
echo 11>3 // print 1
echo 11 == 11 // print 1
echo 10>=12 // print nothing because it is false
This happening becuase a boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string).

Why is 1 == '1,2' true? [duplicate]

This question already has answers here:
Comparing String to Integer gives strange results
(5 answers)
Closed 8 years ago.
Just curious how PHP type casting work for this case.
var_dump(1 == '1,2') // boolean(true)
That is because 1 is an integer here and when it is compared to a string 1,2 , this string will be casted to an integer , which returns 1.
How does casting a string 1,2 return 1 ?
echo int('1,2'); // prints 1
So when it is compared to your 1 , this will be obviously returning true on your var_dump
From the PHP Docs.. (Basic Comparison Test)
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.
Source
It's interpreted as:
var_dump(1 === (int) '1,2');
"1,2" casted to int will return 1, as anything after last parsed digit is being cutted off (,2 in this case).
Remember that comma (,) is not a decimal point separator, dot (.) is:
var_dump((float) '1,3', (float) '1.3');
Results in:
(float) 1
(float) 1.3
Casting can be often very unintuitive, that's why you should almost always use === operator, which doesn't create casts.
If you use ==, php will type cast the right side value to the left side value.
In this case '1,2' will be type cast to 1 and return true.
Even var_dump( 1== "1dfuiekjdfdsfdsfdsfdsfsdfasfsadf" ); will return true.

if/else not working as expected

I have the following code:
$posthandlerResult = reserveerForm_posthandler(decideWhichSectionlist());
if($posthandlerResult=='go2paypage'){
echo 1;
}elseif($posthandlerResult===true){
echo 2;
}else{
echo 3;
}
This is the value of $posthandlerResult (I did this before I did the if/else):
var_dump( $posthandlerResult); // -> bool(true)
What am I expecting? An echo with the number 2. However, im getting number 1. I've been looking at this too long now, why wont this work?
You may use the ===-operator to check for the correct type, too.
The == checks, if the two expressions evaluate to the same value. Interpreted as a bool your string evaluates to true.
The first of your operands is a bool-value, so the second operand is interpreted as a bool, too. A non-empty and not zero string evaluates to boolean true.
You can look up the operator-behaviour for string and bool comparisons here: http://www.php.net/manual/en/language.operators.comparison.php
When using 'if (true == 'someString')', any string that isn't empty or the value 0, will equate to true (so this if statement will be true), see here:
http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

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";
?>

Categories