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:
<?php $a = 3 + 4 + 5 - 2; //from w ww . ja v a 2s. com var_dump($a); // 10 ?>
You can build them combining an arithmetic operator and the assignment operator.
<?php $a = 13; //from ww w . ja v a 2 s . c o m $a += 14; // same as $a = $a + 14; var_dump($a); $a -= 2; // same as $a = $a - 2; var_dump($a); $a *= 4; // same as $a = $a * 4; var_dump($a); ?>