PHP Reference ยท Operators
PHP assignment operators
Reference for PHP assignment operators: =, compound operators like += and .=, ??=, assignment by reference =& and how assignment returns a value.
The assignment operator = stores a value in a variable, array element or property. The compound operators (+=, -=, *=, /=, %=, **=, .=, &=, |=, ^=, <<=, >>= and ??=) combine an operation with assignment: $a += 5 means $a = $a + 5, but $a is only evaluated once.
An assignment is an expression and its value is the assigned value, so $a = $b = 0 works and if (($n = count($list)) > 0) is valid. Scalars and arrays are copied on assignment. Objects are assigned as handles, so two variables point to the same object.
$total = 10; $total += 5; // 15 $name ??= "guest";
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$var = expression; $var op= expression; // op: + - * / % ** . & | ^ << >> ?? $var = &$other; // by reference
| Operator | Equivalent |
|---|---|
+= -= *= /= %= **= |
Arithmetic with the left operand, then store |
.= |
Append a string |
&= |= ^= <<= >>= |
Bitwise operation, then store |
??= |
Assign only if the left side is unset or null (PHP 7.4) |
=& |
Make both names refer to the same value |
Return value: the assigned value. ??= evaluates to the final value of the left side.
Usage notes
=is not==.if ($a = 5)assigns and is always true. Turn on editor warnings for this.- Right associative.
$a = $b = 3assigns to$bfirst. - Undefined variables.
$undefined += 1raises a warning and treats the variable asnull.??=does not warn. ??=is lazy. The right side is only evaluated when an assignment happens. See??.- Arrays are copied lazily (copy on write), so assigning large arrays is cheap until you change one.
- References (
=&) are rarely needed. They can surprise you inforeachloops; unset the reference variable afterwards. - Destructuring with
[$a, $b] = ...is also an assignment. Seelist. - Type juggling.
$s = "5"; $s += 1;turns the string into an integer.