Home PHP What is the difference between == and === in PHP?

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

Author

Date

Category

In PHP, the == (equality) and === (identity) are two different comparison operators used to evaluate equality between values. Here’s the difference between them:

  1. == (Equality Operator):
  • The == operator checks if two values are equal, regardless of their data types.
  • It performs type coercion, meaning it tries to convert the values to a common type before comparing them.
  • If the compared values are different data types, PHP will attempt to convert them to a common type based on certain rules. For example, when comparing a string and an integer, PHP will convert the string to an integer before performing the comparison.
  • Example: $x == $y returns true if $x and $y are equal after type coercion, and false otherwise.
  1. === (Identity Operator):
  • The === operator checks if two values are identical, both in value and data type.
  • It does not perform type coercion and requires both the value and data type to be the same for the comparison to be true.
  • Example: $x === $y returns true if $x and $y are equal in value and data type, and false otherwise.

Here’s an example to illustrate the difference between the two operators:

$x = 5; // integer
$y = "5"; // string

var_dump($x == $y); // Outputs: bool(true), since "5" (string) is equal to 5 (integer) after type coercion
var_dump($x === $y); // Outputs: bool(false), since the data types are different (integer vs. string)
PHP


In summary, the == operator checks for equality after type coercion, while the === operator checks for identity, considering both value and data type. It is generally recommended to use === for precise comparisons to avoid unexpected results due to type coercion.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts