This question already has answers here:
Why does PHP consider 0 to be equal to a string?
(9 answers)
Closed 6 years ago.
A friend of mine recently showed my the following snippet
<?php
$a = 0;
$b = 'x';
if(FALSE == $a && $a == $b && $b == TRUE) {
echo 'WTF!?';
}
?>
which ouputs WTF!?
I understand why FALSE == $a holds, because zero is considered to be FALSE. I also understand why $b == TRUE holds, because the string is not empty. But I didn't understand why $a == $b is true, could somebody explain to me what type coercion rules play together here to get this rather amusing result?
when you compare $a == $b you are comparing an int with a string so PHP tries to parse the string into an int if it fails which happened in this case, it changes its value to 0 and then 0 == 0 returns true. Check this:
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. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
Change this condition $a == $b to $a === $b to compare the type as well. Hope this helps.
Related
<?php
$test = "-3,-13";
if ($test == -3) {
echo "yay";
} else {
echo "nay";
}
?>
why it always runs through if condition and not going in else condition? I am new to php so do not know what's going on here.
The string is converted into an integer "-3, 46, blala" -> -3 , then the condition is evaluated.
Use the === operator to avoid conversion.
Most of the time, you do not want to let php do the conversion in your place (security problem). Rather, the request is refused.
As PHP documentation says
Example Name Result
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
When we compare a number with a string, the string is converted to a number and the comparison performed numerically.
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
https://www.php.net/manual/en/language.operators.comparison.php
This question already has answers here:
Comparing String to Integer gives strange results
(5 answers)
Closed 6 years ago.
I have this code:
$test = 0;
if ($test == "on"){
echo "TRUE";
}
Result of this code will be:
TRUE
WHY??? My version of PHP: 5.4.10.
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. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
$test = 0;
if ($test === "on"){
echo "TRUE";
}
PHP will convert the string to number to compare. Using ===, will compare the value as well as the type of data.
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
Docs
Because you are comparing $test with string value not binary value, if you want to compare with string value, try with === comparison, for
value + dataType.
In your example, var_dump(0=="on"); always return bool(true).
But when you use var_dump(0==="on"); it will give you bool(false).
Example from PHP Manual:
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
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. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
So use "===" for comparision.
Refer the link : http://php.net/manual/en/language.operators.comparison.php
This is because your are doing ==
0 is integer so in this on converted to int which is 0
So your if statement looks like 0==0
For solution You have to use ===
if ($test === "on")
In PHP, loose comparison between integer and non-numeric string (i.e string which cannot be interpreted as numeric, such as "php" or in your case "on") will cause string to be interpreted as integer with value of 0. Note that numeric "43", "1e3" or "123" is a numeric string and will be correctly interpreted as numeric value.
I know this is weird.
This question already has answers here:
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 4 months ago.
I've noticed someone using the PHP operator === which I can't make sense out of. I've tried it with a function, and it corresponds in crazy ways.
What is the definition of this operator? I can't even find it in the declaration of PHP operators.
$a === $b (Identical)
TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
PHP Docs
http://www.php.net/ternary
$a == $b Equal TRUE if $a is equal to $b, except for (True == -1) which is still True.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
> "5" == 5;
True
> "5" === 5;
False
You can read here, short summary:
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
In PHP you may compare two values using the == operator or === operator. The difference is this:
PHP is a dynamic, interpreted language that is not strict on data types. It means that the language itself will try to convert data types, whenever needed.
echo 4 + "2"; // output is 6
The output is integer value 6, because + is the numerical addition operator in PHP, so if you provide operands with other data types to it, PHP will first convert them to their appropriate type ("2" will be converted to 2) and then perform the operation.
If you use == as the comparison operator with two operands that might be in different data types, PHP will convert the second operand type, to the first's. So:
4 == "4" // true
PHP converts "4" to 4, and then compares the values. In this case, the result will be true.
If you use === as the comparison operator, PHP will not try to convert any data types. So if the operands' types are different, then they are NOT identical.
4 === "4" // false
$x == $y is TRUE if the value of the $x and $y are same:
$x = 1; //int type
$y = "1"; //string type
if ($x == $y) {
// This will execute
}
$x === $y TRUE if the value of the $x and $y are same and type of $x and $y are same:
$x = 1; //int type
$y = "1"; //string type
if ($x === $y) {
// This will not execute
}
You'll see this operator in many dynamically typed languages, not just PHP.
== will try to convert whatever it's dealing with into types that it can compare.
=== will strictly compare the type and value.
In any dynamically typed language you have to be careful with ==, you can get some interesting bugs.
The ternary === is less convenient, but it's safer. For comparisons you should always give some additional thought to whether it should be === or ==
The triple equals sign === checks to see
whether two variables are equal and of the same type.
For PHP, there many different meanings a zero can take
it can be a Boolean false
it could be a null value
It could really be a zero
So === is added to ensure the type and the value are the same.
See Double and Triple equals operator in PHP that I got for googling on "PHP three equals operator".
At one point it says that:
A double = sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
A triple = sign is a comparison to see whether two variables / expresions / constants are equal AND have the same type - i.e. both are strings or both are integers.
It also gives an example to explain it.
"===" matching the value in the variable as well as data type of the variable.
This question already exists:
Closed 13 years ago.
Possible Duplicate:
php == vs === operator
What's the difference between !== and != in PHP?
!== is strict not equal and which does not do type conversion
!= is not equal which does type conversion before checking
=== AND !== checks if the values compared have the same type (eg: int, string, etc.) and have the same values
While...
== AND != only compares the values
"1" != 1 // False
"1" !== 1 // True
It's a type thing. !== takes into account the types of its operands, while != does not (the implicit conversion makes the first conditional false).
== is only true if the values are equal.
=== is only true if the values and types are equal.
the triple equal also make sure the two variable are from the same type
1 == `1` // is ok
1 === `1` // is not same.
Both are comparion operators
$a !== $b Return TRUE if $a is not equal to $b, or they are not of the same type.
$a != $b Return TRUE if $a is not equal to $b.
In PHP, ($myvariable==0)
When $myvariable is zero, the value of the expression is true; when $myvariable is null, the value of this expression is also true. How can I exclude the second case? I mean I want the expression to be true only when $myvariable is zero. Of course I can write
($myvariable != null && $myvariable == 0)
But is there other elegant way to do this?
$myvariable === 0
read more about comparison operators.
You hint at a deep question: when should an expression be true?
Below, I will explain why what you are doing isn't working and how to fix it.
In many languages null, 0, and the empty string ("") all evaluate to false, this can make if statements quite succinct and intuitive, but null, 0, and "" are also all of different types. How should they be compared?
This page tells us that if we have two variables being compared, then the variables are converted as follows (exiting the table at the first match)
Type of First Type of Second Then
null/string string Convert NULL to "", numerical/lexical comparison
bool/null anything Convert to bool, FALSE < TRUE
So you are comparing a null versus a number. Therefore, both the null and the number are converted to boolean. This page tells us that in such a conversion both null and 0 are considered FALSE.
Your expression now reads, false==false, which, of course, is true.
But not what you want.
This page provides a list of PHP's comparison operators.
Example Name Result
$a == $b Equal TRUE if $a equals $b after type juggling.
$a === $b Identical TRUE if $a equals $b, AND they are of the same type.
$a != $b Not equal TRUE if $a not equals $b after type juggling.
$a <> $b Not equal TRUE if $a not equals $b after type juggling.
$a !== $b Not identical TRUE if $a not equals $b, or they are not of the same type.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than/equal TRUE if $a is less than or equal to $b.
$a >= $b Greater than/equal TRUE if $a is greater than or equal to $b.
The first comparator is the comparison you are using now. Note that it performs the conversions I mentioned earlier.
Using the second comparator will fix your problem. Since a null and a number are not of the same type, the === comparison will return false, rather than performing type conversion as the == operator would.
Hope this helps.
To identify as null or zero by:
is_int($var) if a variable is a number or a numeric string. To identify Zero, use is_numeric($var) is also the solution or use $var === 0
is_null($var) if a variable is NULL
Try ($myvariable === 0) which will not perform type coercion.
Use the php function is_null( ) function along with the === operator. !== also works the way you'd expect.
The second solution wouldn't work either. The === operator is the solution to your problem.
If your zero could be a string, you should also considere checking the "zero string"
($myvariable === 0 || $myvariable === '0')
I hade faced a similar issue in one of my projects, with a minor difference that I was also using the values ZERO as a valid value for my condition. here's how I solved it using simple logic to separate NULL from zero and other values.
if (gettype($company_id) === 'NULL') {
$company = Company::where('id', Auth::user()->company_id)->first();
} else {
$company = Company::where('id', $company_id)->first();
}
$myvariable===0
$a === $b
Identical TRUE if $a is equal to $b, and they are of the same type
There's an is_null function, but this will just replace your $myvariable!=null
For my case i found this soulution and it works for me :
if ($myvariable === NULL) {
codehere...
}