Operators in PHP

Once you have a few variables you can make operations with them:

$base = 20;
$height = 10;

$area = $base * $height;

The * I used to multiply $base per $height is the multiplication operator.

We have quite a few operators, let’s do a quick roundup of the main ones.

To start with, here are the arithmetic operators: +, -, *, / (division), % (remainder) and ** (exponential)

We have the assignment operator =, which we already used to assign a value to a variable.

Next up we have comparison operators, like <, >, <=, >=. Those work like they do in math.

2 < 1; //false
1 <= 1; // true
1 <= 2; // true

== returns true if the two operands are equal.

=== returns true if the two operands are identical.

What’s the difference?

You’ll find it with experience, but for example

1 == '1'; //true
1 === '1'; //false

We also have != to detect if operands are not equal:

1 != 1; //false
1 != '1'; //false
1 != 2; //true

//hint: <> works in the same way as !=, 1 <> 1

and !== to detect if operands are not identical:

1 !== 1; //false
1 !== '1'; //true

Logical operators work with boolean values:

// Logical AND with && or "and"

true && true; //true
true && false; //false
false && true; //false
false && false; //false

true and true; //true
true and false; //false
false and true; //false
false and false; //false

// Logical OR with || or "or"

true || true; // true
true || false //true
false || true //true
false || false //false

true or true; // true
true or false //true
false or true //true
false or false //false

// Logical XOR (one of the two is true, but not both)

true xor true; // false
true xor false //true
false xor true //true
false xor false //false

We also have the not operator:

$test = true

!$test //false

I used the boolean values true and false here, but in practice you’ll use expressions that evaluate to either true or false, for example:

1 > 2 || 2 > 1; //true

1 !== 2 && 2 > 2; //false

All of the operators listed above are binary, meaning they involve 2 operands.

PHP also has 2 unary operators: ++ and --:

$age = 20;
$age++;
//age is now 21

$age--;
//age is now 20

Download my free PHP Handbook!