Combined Assignment etc
suggest changeThe combined assignment operators are a shortcut for an operation on some variable and subsequently assigning this new value to that variable.
Arithmetic:
$a = 1; // basic assignment
$a += 2; // $a = $a + 2; $a is now 3
$a -= 1; // $a is now 2
$a *= 2; // $a is now 4
$a /= 2; // $a is now 2
$a %= 5; // $a is now 2 (remainder of 2 % 5)
// Array union keeps keys that already exist on the left.
$arrOne = array(1); // [0 => 1]
$arrTwo = array(2); // [0 => 2]
$arrOne += $arrTwo; // still [0 => 1]
Processing Multiple Arrays Together
$a **= 2; // $a is now 4 (2 ** 2). The **= operator requires PHP 5.6 or later.
Combined concatenation and assignment of a string:
$a = "a";
$a .= "b"; // $a => "ab"
Combined binary bitwise assignment operators:
$a = 0b00101010; // $a now is 42
$a &= 0b00001111; // $a now is (00101010 & 00001111) => 00001010 (bitwise and)
$a |= 0b00100010; // $a now is (00001010 | 00100010) => 00101010 (bitwise or)
$a ^= 0b10000010; // $a now is (00101010 ^ 10000010) => 10101000 (bitwise xor)
$a >>= 3; // $a now is (10101000 >> 3) => 00010101 (shift right by 3)
$a <<= 1; // $a now is (00010101 << 1) => 00101010 (shift left by 1)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents