PHP - Operator Assignment operators


Here is how the basic assignment operator ( = ) can be used to assign a value to a variable:

$test_var = 1.23;

The preceding expression itself evaluates to the value of the assignment: 1.23.

This is because the assignment operator produces a value as well as carrying out the assignment operation.

You can write code such as:

$another_var = $test_var = 1.23;

Both $test_var and $another_var now contain the value 1.23

The equals sign = can be combined with other operators to give you a combined assignment operator.

The combined assignment operators, such as +=, -=, give you a shorthand method for performing typical arithmetic operations.

For example, you can write:

$first_number += $second_number;

rather than:

$first_number = $first_number + $second_number;

This works for other kinds of operators.

For example, the concatenation operator can be combined with the equals sign as .=

$a = "a";
$b = "b";
$a .= $b;                 // $a now contains  "ab"

The assignment operator assigns the result of an expression to a variable.

An expression can be as simple as a number, or, the result of a series of arithmetic operations.

The following example assigns the result of an expression to a variable:


    $a = 3 + 4 + 5 - 2; //from w  w  w.ja va 2s  .c o m
    var_dump($a); // 10 


You can build them combining an arithmetic operator and the assignment operator.


    $a = 13; /*from w ww  .j  a v a  2s  .co  m*/
    $a += 14; // same as $a = $a + 14; 
    $a -= 2; // same as $a = $a - 2; 
    $a *= 4; // same as $a = $a * 4;