Operators
Tutorials

Operators are how you perform mathematical operations or manipulations on variables.

<?php
$a = 10;
$b = 3;

// Basic Arithmetic
echo $a + $b;    // Addition: 13
echo $a - $b;    // Subtraction: 7
echo $a * $b;    // Multiplication: 30
echo $a / $b;    // Division: 3.3333333333333

// Modulus (The remainder of a division)
echo $a % $b;    // Outputs 1 (because 3 goes into 10 three times, with 1 left over)

// Exponentiation (Power)
echo $a ** $b;   // Outputs 1000 (10 to the power of 3)

Concatenation Operator (Dot)

If you have experience with languages such as Javascript, the concatenation operator . (dot) might catch you out at first if you are used to concatenating with + (plus).

The reason PHP uses . to concatenate values is because of "type juggling", that is, where a string containing a number, such as "4" might get converted to a number when using mathematical operators such as +.

<?php
echo "4" + "4"; // this outputs 8 (int)

echo "hello" + "world"; // this causes an error

echo "4" . "4"; // this outputs 44 (string)

Notice how using the . operator allows us to be specific about our intentions, regardless of type.

To Top