The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").
The value of an assignment expression is the value assigned. That is, the value of "$a = 3
" is 3. This allows you to do some tricky things:
In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:
Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.
An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference. Objects may be explicitly copied via the clone keyword.
Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.
Example #1 Assigning by reference
The new operator returns a reference automatically, as such assigning the result of new by reference is an error.
The above example will output:
More information on references and their potential uses can be found in the References Explained section of the manual.
Example | Equivalent | Operation |
---|---|---|
$a += $b | $a = $a + b | Addition |
$a -= $b | $a = $a - $b | Subtraction |
$a *= $b | $a = $a * $b | Multiplication |
$a /= $b | $a = $a / $b | Division |
$a %= $b | $a = $a % $b | Modulus |
Example | Equivalent | Operation |
---|---|---|
$a &= $b | $a = $a & $b | Bitwise And |
$a |= $b | $a = $a | $b | Bitwise Or |
$a ^= $b | $a = $a ^ $b | Bitwise Xor |
$a <<= $b | $a = $a << $b | Left Shift |
$a >>= $b | $a = $a >> $b | Right Shift |
Example | Equivalent | Operation |
---|---|---|
$a .= $b | $a = $a . $b | String Concatenation |
$a ??= $b | $a = $a ?? $b | Null Coalesce |
© 1997–2020 The PHP Documentation Group
Licensed under the Creative Commons Attribution License v3.0 or later.
https://www.php.net/manual/en/language.operators.assignment.php