Not equal to != and !== in PHP - php

I've always done this: if ($foo !== $bar)
But I realized that if ($foo != $bar) is correct too.
Double = still works and has always worked for me, but whenever I search PHP operators I find no information on double =, so I assume I've always have done this wrong, but it works anyway. Should I change all my !== to != just for the sake of it?

== and != do not take into account the data type of the variables you compare. So these would all return true:
'0' == 0
false == 0
NULL == false
=== and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:
'0' === 0
false === 0
NULL === false
You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():
// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false); // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned

!== should match the value and data type
!= just match the value ignoring the data type
$num = '1';
$num2 = 1;
$num == $num2; // returns true
$num === $num2; // returns false because $num is a string and $num2 is an integer

$a !== $b TRUE if $a is not equal to $b, or they are not of the same type
Please Refer to http://php.net/manual/en/language.operators.comparison.php

You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.

Related

Why PHP condition getting true even if i am checking equal to

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

How can i detect if (float)0 == 0 or null in PHP

If variable value is 0 (float) it will pass all these tests:
$test = round(0, 2); //$test=(float)0
if($test == null)
echo "var is null";
if($test == 0)
echo "var is 0";
if($test == false)
echo "var is false";
if($test==false && $test == 0 && $test==null)
echo "var is mixture";
I assumed that it will pass only if($test == 0)
Only solution I found is detect if $test is number using function is_number(), but can I detect if float variable equal zero?
Using === checks also for the datatype:
$test = round(0, 2); // float(0.00)
if($test === null) // false
if($test === 0) // false
if($test === 0.0) // true
if($test === false) // false
Use 3 equal signs rather than two to test the type as well:
if($test === 0)
If you use=== instead of == it will compare as well as get the data types errors manage...Can you post your answer while using === ? Please check the difference between this two here
When comparing values in PHP for equality you can use either the == operator or the === operator. What’s the difference between the 2? Well, it’s quite simple. The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra “=”) actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.).

php variables comparison == vs ===

this is code:
$s = 0;
$d = "dd";
if ($s == $d) {
var_dump($s);
die(var_dump($d));
}
result is:
int 0
string 'dd' (length=2)
Please explain why.
why ($s == $d) results as true?
Of course, if === is used it will results as false but why this situation requires ===?
Shouldn't it be returned false in both situations?
Because (int)$d equals with 0 and 0=0
you must use strict comparison === for different character tyes (string) with (int)
Your $d is automatically converted to (int) to have something to compare.
When you compare a number to a string, the string is first type juggled into a number. In this case, dd ends up being juggled into 0 which means that it equates to true (0==0).
When you change the code to:
<?php
$s = 1;
$d = "dd";
if ($s == $d)
{
var_dump($s);
die(var_dump($d));
}
?>
You will find that it doesn't pass the if statement at all.
You can more details by reading up on comparison operators and type juggling.
The string "dd" is converted to int, and thus 0.
Another example :
if ( "3kids" == 3 )
{
return true;
}
And yes, this returns true because "3kids" is converted to 3.
=== does NOT auto convert the items to the same type.
Also : 0 == false is correct, but 0 === false is not.
See : http://php.net/manual/en/language.types.type-juggling.php
The string will try to parsed into a number, returns 0 if it is not in right number format.
As seen in the php website :
http://php.net/manual/en/language.operators.comparison.php
var_dump(0 == "a"); // 0 == 0 -> true
In PHP, == should be pronounce "Probably Equals".
When comparing with ==, PHP will juggle the file-types to try and find a match.
A string with no numbers in it, is evaluated to 0 when evaluated as an int.
Therefore they're equals.

Why does (0 == 'Hello') return true in PHP?

Hey, if you have got the following code and want to check if $key matches Hello I've found out, that the comparison always returns true if the variable is 0. I've came across this when an array for a special key and wondered why it's wasn't working as expected.
See this code for an example.
$key = 1;
if ($key != 'Hello') echo 'Hello'; //echoes hello
$key = 2;
if ($key != 'Hello') echo 'Hello'; //echoes hello
$key = 0;
if ($key != 'Hello') echo '0Hello'; //doesnt echo hello. why?
if ($key !== 'Hello') echo 'Hello'; //echoes hello
Can anyone explain this?
The operators == and != do not compare the type. Therefore PHP automatically converts 'Hello' to an integer which is 0 (intval('Hello')). When not sure about the type, use the type-comparing operators === and !==. Or better be sure which type you handle at any point in your program.
Others have already answered the question well. I only want to give some other examples, you should be aware of, all are caused by PHP's type juggling. All the following comparisons will return true:
'abc' == 0
0 == null
'' == null
1 == '1y?z'
Because i found this behaviour dangerous, i wrote my own equal method and use it in my projects:
/**
* Checks if two values are equal. In contrast to the == operator,
* the values are considered different, if:
* - one value is null and the other not, or
* - one value is an empty string and the other not
* This helps avoid strange behavier with PHP's type juggling,
* all these expressions would return true:
* 'abc' == 0; 0 == null; '' == null; 1 == '1y?z';
* #param mixed $value1
* #param mixed $value2
* #return boolean True if values are equal, otherwise false.
*/
function sto_equals($value1, $value2)
{
// identical in value and type
if ($value1 === $value2)
$result = true;
// one is null, the other not
else if (is_null($value1) || is_null($value2))
$result = false;
// one is an empty string, the other not
else if (($value1 === '') || ($value2 === ''))
$result = false;
// identical in value and different in type
else
{
$result = ($value1 == $value2);
// test for wrong implicit string conversion, when comparing a
// string with a numeric type. only accept valid numeric strings.
if ($result)
{
$isNumericType1 = is_int($value1) || is_float($value1);
$isNumericType2 = is_int($value2) || is_float($value2);
$isStringType1 = is_string($value1);
$isStringType2 = is_string($value2);
if ($isNumericType1 && $isStringType2)
$result = is_numeric($value2);
else if ($isNumericType2 && $isStringType1)
$result = is_numeric($value1);
}
}
return $result;
}
Hope this helps somebody making his application more solid, the original article can be found here:
Equal or not equal
pretty much any non-zero value gets converted to true in php behind the scenes.
so 1, 2,3,4, 'Hello', 'world', etc would all be equal to true, whereas 0 is equal to false
the only reason !== works is cause it is comparing data types are the same too
Because PHP does an automatic cast to compare values of different types. You can see a table of type-conversion criteria in PHP documentation.
In your case, the string "Hello" is automatically converted to a number, which is 0 according to PHP. Hence the true value.
If you want to compare values of different types you should use the type-safe operators:
$value1 === $value2;
or
$value1 !== $value2;
In general, PHP evaluates to zero every string that cannot be recognized as a number.
In php, the string "0" is converted to the boolean FALSE http://php.net/manual/en/language.types.boolean.php

What does === do in PHP

I have been programming in PHP for a while but I still dont understand the difference between == and ===. I know that = is assignment. And == is equals to. So what is the purpose of ===?
It compares both value and type equality.
if("45" === 45) //false
if(45 === 45) //true
if(0 === false)//false
It has an analog: !== which compares type and value inequality
if("45" !== 45) //true
if(45 !== 45) //false
if(0 !== false)//true
It's especially useful for functions like strpos - which can return 0 validly.
strpos("hello world", "hello") //0 is the position of "hello"
//now you try and test if "hello" is in the string...
if(strpos("hello world", "hello"))
//evaluates to false, even though hello is in the string
if(strpos("hello world", "hello") !== false)
//correctly evaluates to true: 0 is not value- and type-equal to false
Here's a good wikipedia table listing other languages that have an analogy to triple-equals.
It is true that === compares both value and type, but there is one case which hasn't been mentioned yet and that is when you compare objects with == and ===.
Given the following code:
class TestClass {
public $value;
public function __construct($value) {
$this->value = $value;
}
}
$a = new TestClass("a");
$b = new TestClass("a");
var_dump($a == $b); // true
var_dump($a === $b); // false
In case of objects === compares reference, not type and value (as $a and $b are of both equal type and value).
The PHP manual has a couple of very nice tables ("Loose comparisons with ==" and "Strict comparisons with ===") that show what result == and === will give when comparing various variable types.
It will check if the datatype is the same as well as the value
if ("21" == 21) // true
if ("21" === 21) // false
=== compares value and type.
== doesn't compare types, === does.
0 == false
evaluates to true but
0 === false
does not
Minimally, === is faster than == because theres no automagic casting/coersion going on, but its so minimal its hardly worth mentioning. (of course, I just mentioned it...)
It's a true equality comparison.
"" == False for instance is true.
"" === False is false

Categories