PHP Operators
Operators are symbols that change or combine values. PHP uses ** for power and % for a remainder.
Power with **
A power multiplies a number by itself. This code works out 2 times 2 times 2.
<?php
$power = 2 ** 3;
echo "$power\n";++ and -- change a value
The value starts at 5 in the code. Each operator moves the stored value by one.
<?php
$count = 5;
$count++;
echo "$count\n";
$count--;
echo "$count\n";Compound updates with += and *=
A compound operator uses the old value in the update. The new value is stored back in the same variable.
<?php
$score = 10;
$score += 5;
echo "$score\n";
$score *= 2;
echo "$score\n";Growing a string with .=
The .= operator adds text to the end of a string. The string grows one step at a time.
<?php
$word = "Hi";
$word .= " there";
echo "$word\n";
$word .= "!";
echo "$word\n";Remainder with %
A remainder is what stays left over after division. Dividing 10 by 3 leaves 1, and dividing 9 by 3 leaves 0.
<?php
$first = 10 % 3;
$second = 9 % 3;
echo "$first\n";
echo "$second\n";Example
<?php
$score = 20;
$score += 10;
echo "After adding 10 the score is $score\n";
$score -= 5;
echo "After taking 5 the score is $score\n";
$score *= 2;
echo "After doubling the score is $score\n";
$score++;
echo "After one more point the score is $score\n";Key points
- The ** operator raises a number to a power.
- The ++ operator adds 1 to a variable.
- The -- operator takes 1 away from a variable.
- The += operator adds a value to a variable and stores the total.
- The -= operator subtracts a value from a variable and stores the result.
- The *= operator multiplies a variable by a value and stores the product.
- The .= operator adds text to the end of a string and stores the longer string.
- The % operator gives the remainder after division.
In this example, the score starts at 20. The += operator adds 10 and the score becomes 30. The -= operator takes away 5 and the score becomes 25. The *= operator doubles it to 50. The ++ operator adds one more point and the score ends at 51. Each step prints the score right after its update.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
A variable named $count holds 4. What value does $count hold after the line $count *= 3 runs?