PHP Assignment Operators

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP Assignment Operators

Description

Assignment operators allow writing a value to a variable. The first operand must be a variable and the basic assignment operator is "=". The value of an assignment expression is the final value assigned to the variable. In addition to the regular assignment operator "=", several other assignment operators are composites of an operator followed by an equal sign.

Interestingly all five arithmetic operators have corresponding assignment operators, Here is the list.

  • +=

  • -=

  • *=

  • /=

  • %=

The following table discussed more details of the said assignment operators.

Shorthand

Expression

Description

$a+= $b

$a = $a + $b

Adds 2 numbers and assigns the result to the first.

$a-= $b

$a = $a -$b

Subtracts 2 numbers and assigns the result to the first.

$a*= $b

$a = $a*$b

Multiplies 2 numbers and assigns the result to the first.

$a/= $b

$a = $a/$b

Divides 2 numbers and assigns the result to the first.

$a%= $b

$a = $a%$b

Computes the modulus of 2 numbers and assigns the result to the first.

Example :

view plaincopy to clipboardprint?

  1. $x1=100;  

  2. $x2=200;  

  3. $x3=300;  

  4. $x4=400;  

  5. $x5=500;  

  6. $x1+= 100;  

  7. echo " $x1 
    ";  

  8. $x2-= 200;  

  9. echo " $x2 
    ";  

  10. $x3*= 300;  

  11. echo " $x3 
    ";  

  12. $x4/= 400;  

  13. echo " $x4 
    ";  

  14. $x5%= 500;  

  15. echo " $x5 
    ";  

  16. $x=($y=11)+9;  

  17. echo " Value of x & y is :  $x  $y 
    ";  

  18. ?>  

Output :

200
0
90000
1
0
Value of x & y is : 20 11