The Most Active and Friendliest
Affiliate Marketing Community Online!

“Adavice”/  “1Win

Tip : difference between =, == and === in php

D

dman_2007

Guest
Confusion between = and == is usually a frequent source of error in scripts written by newbies. This often hard to detect (for newbies) problem arises when they use = assignment operator thinking of it as a comparsion operator in the if control stucture. For example, take a look at the following example :

Code:
<?php
  $user_input = $_GET['user_input'];
  
  if($user_input = 5)
  {
    echo 'You entered 5';     
  }
?>

When executed, the above code will always print "You entered 5" regardless of the input given by the user. The reason, of course, is the incorrect use of assignment operator instead of comparison operator in the if conditional expression. The assignment operator replaces the previous value stored in the $user_input variable with 5 and then it is converted to a boolean value which comes out to be true and hence the statement in braces is always executed. The correct code is :

Code:
<?php
 $user_input = $_GET['user_input'];
  
  if($user_input == 5)
  {
    echo 'You entered 5';     
  }
?>

running above code, it'll print "You entered 5" only when the user actually gives 5 as input.

=== is also a comparison operator similar to == as both check for operand equality, but it is a bit more stricter. == operator considers its operand as equal when both of them have same value whereas === operator will consider them equal only when they have same type as well. For example,

Code:
<?php
   $value1 = 7;
   $value2 = "7";
   
   if($value1 == $value2)
   {
     echo 'According to == operator, $value1 and $value2 are equal.';
   }
   
  if($value1 === $value2)
  {
    echo 'According to === operator, $value1 and $value 2 are equal.';
  }
?>

When the above code is executed, only first echo statement will be executed.
 
banners
Back