Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Operators

Operators are symbols that act on values: they add, compare and combine conditions. The result of an operator can be printed or stored in a variable.

What an operator is

An operator sits between two values and produces a result. The simplest example is addition:

<?php
 
echo 7 + 2; // 9

Here + is the operator, and 7 and 2 are the values it works on.

Arithmetic operators

OperatorActionExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division7 / 23.5
%Remainder of a division7 % 21
**Raising to a power7 ** 249

The remainder is often used to check parity: an even number leaves a remainder of zero when divided by 2.

<?php
 
echo 7 % 2; // 1

Operator precedence

As in mathematics, multiplication and division happen before addition and subtraction:

<?php
 
echo 2 + 3 * 4; // 14

Parentheses change the order:

<?php
 
echo (2 + 3) * 4; // 20

When in doubt, add parentheses. They cost nothing at run time and make the code easier to read.

Compound assignment

$total = $total + 5 can be shortened to $total += 5. The same shorthand exists for the other operations, and ++ and -- change a value by one:

<?php
 
$total = 10;
$total += 5;  // 15
$total *= 2;  // 30
$total++;     // 31
 
echo $total;

Comparison operators

A comparison always produces a boolean — true or false:

<?php
 
var_dump(5 > 3);     // bool(true)
var_dump(5 <= 3);    // bool(false)
var_dump(5 === 5);   // bool(true)
var_dump(5 !== '5'); // bool(true)

The !== operator means "not equal, taking the type into account": the number 5 and the string '5' are different values.

Logical operators

Logical operators combine several conditions: && is "and", || is "or", ! is "not".

<?php
 
$age = 20;
$hasTicket = true;
 
var_dump($age >= 18 && $hasTicket); // bool(true)
var_dump($age < 18 || !$hasTicket); // bool(false)

An expression with && is true only when both parts are true; with || it is true when at least one part is.

A common mistake

A single = is assignment, not comparison. $a = 5 stores a number in the variable, while $a === 5 checks whether it equals five. Mixing them up inside a condition is a classic bug that is hard to spot.

Thanks for reading!

Donate to the site — we work hard for you.