Curriculum
This tutorial will teach you about the most common PHP assignment operators.
The assignment operator in PHP is represented by the = symbol. The syntax of the assignment operator is shown below:
$variable_name = expression;
A variable to which you want to assign a value is on the left side of the assignment operator (=). A value or an expression is placed on the right side of the assignment operator (=).
When the assignment operator (=) is used, PHP evaluates the expression on the right side first and then assigns the result to the variable on the left side. As an example:
$x = 10; $y = 20; $total = $x + $y;
In this example, we assigned a value of 10 to $x, a value of 20 to $y, and the sum of $x and $y to $total.
In this case, the assignment expression returns a value assigned, which is the result of the expression:
$variable_name = expression;
This means you can use multiple assignment operators in a single statement, such as this:
$x = $y = 20;
PHP evaluates the right-most expression first in this case:
$y = 20
The value of the variable $y is 20.
PHP assigns 20 to $x because the assignment expression $y = 20 returns 20. Following the assignments, $x and $y both equal 20.
You may want to increase a variable by a specific amount from time to time. As an example:
$counter = 1; $counter = $counter + 1;
This is how it works.
To begin, $counter is set to 1.
Then, multiply $counter by 1 and assign the result to $counter.
The value of $counter after the assignments is 2.
PHP includes the arithmetic assignment operator +=, which can perform the same function but with less code. As an example:
$counter = 1; $counter += 1;
The expression $counter += 1 corresponds to the expression $counter = $counter + 1.
Other arithmetic assignment operators are available in PHP in addition to the += operator. The table below depicts all of the arithmetic assignment operators:
Operator | Example | Equivalent | Operation |
---|---|---|---|
+= | $x += $y | $x = $x + $y | Addition |
-= | $x -= $y | $x = $x – $y | Subtraction |
*= | $x *= $y | $x = $x * $y | Multiplication |
/= | $x /= $y | $x = $x / $y | Division |
%= | $x %= $y | $x = $x % $y | Modulus |
**= | $z **= $y | $x = $x ** $y | Exponentiation |
To concatenate two strings, PHP employs the concatenation operator (.). As an example:
<?php $greeting = 'Hello '; $name = 'John'; $greeting = $greeting . $name; echo $greeting;
Output
Hello John
You can concatenate two strings and assign the result string to a variable by using the concatenation assignment operator. As an example:
<?php $greeting = 'Hello '; $name = 'John'; $greeting .= $name; echo $greeting;