Assignment =
vs Equal ==
vs Identical ===
Operators in PHP
Assignemtn Operator =
A single equal sign =
is the basic assignment operator in PHP.
Don't think this sign as "equal to".
The variable on left side of =
gets set to the value of the expression on the rights.
It is used to set a variable equal to a value or set a variable to another variable's value.
Example =
<?php $a = 123; //assigned 123 to variable $a $b = $a; // assigned $a ?>
In above example $a
and $b
has the same value 123
.
Equal Operator ==
The double equal sign ==
is a comparison operator called Equal Operator, it accepts two inputs to compare and return true
if the values are same and return false
if values are not same.
Keep in mind that the equality operator ==
is different than the assignment operator =
. The assignment operator changes the variable on the left to have a new value, while the equal operator ==
tests for equality and returns true or false.
Example ==
<?php $a = 123; //php integer $b = '123'; //php string if ($a == $b) { echo 'Values are same'; } else { echo 'Values are not same'; } ?>
The above example prints Values are same
.
Identical Operator ===
Identical operator ===
allows for stricter comparison between variables. It only returns true if the two variables or values being compared hold the same information and are of the same data type.
Example ===
<?php $a = 123; //php integer $b = '123'; //php string if ($a === $b) { echo 'Values and types are same'; } else { echo 'Values and types are not same'; } ?>
The above example prints Values and types are not same
because $a
data type is an integer and $b
data type is string, and these data types are not same, ===
compares two things values and type, failure in one returns the false result.
Note alway remember that Equal and Identical operators are not the same thing. Identical matches both a variable's value and datatype, whereas equal matches only value.