Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double equals and tripple equals in php

Tags:

php

I searched on StackOverflow and Google and I can't find the answer to this question:

Should we always use the triple equal in PHP for validation?

For example, I have a variable:

$x = '1';

if($x == 1)  // will work
if($x === 1) // will not

Now, my point is if we need to validate numeric fields like:

if(is_numeric($x) && $x == '1') { will be the equivalent to if($x === 1)

Since === also validate the type, will it be better if we always use the ===?

like image 897
Ken Avatar asked Dec 17 '11 19:12

Ken


People also ask

What is the difference between double equal to and triple equal to in PHP?

The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.

What is triple equal in PHP?

Identical Operator ===The comparison operator called as the Identical operator is the triple equal sign “===”. This operator allows for a much stricter comparison between the given variables or values. This operator returns true if both variable contains same information and same data types otherwise return false.

What is the difference between double == and triple === equals?

Turns out, the difference between them is the double equals allows coercion and the triple equals disallows coercion. They both test equality. One of them allows coercion to occur first and one of them doesn't.

What is the difference between == and === in HTML?

KEY DIFFERENCES:= does not return true or false, == Return true only if the two operands are equal while === returns true only if both values and data types are the same for the two variables.


1 Answers

From http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/

== is useless.

‣ It’s not transitive. "foo" == TRUE, and "foo" == 0… but, of course, TRUE != 0.

‣ == converts to numbers when possible, which means it converts to floats when possible. So large hex strings (like, say, password hashes) may occasionally compare true when they’re not. Even JavaScript doesn’t do this.

‣ For the same reason, "6" == " 6", "4.2" == "4.20", and "133" == "0133". But note that 133 != 0133, because 0133 is octal.

‣ === compares values and type… except with objects, where === is only true if both operands are actually the same object! For objects, == compares both value (of every attribute) and type, which is what === does for every other type. What.

See http://habnab.it/php-table.html

And http://phpsadness.com/sad/47

And http://developers.slashdot.org/comments.pl?sid=204433&cid=16703529

That being said, when you are absolutely sure type is not an issue when you are creating simple expressions, == works well enough in my experience. Just be vigilant.

like image 157
Alex Avatar answered Sep 18 '22 09:09

Alex