php-operadores-en-php

Operators in PHP

  • 4 min

An operator is a symbol that performs an operation on one or more values.

We already have variables (data). Now we need to do things with them: add them, compare them, or decide which one to use. That’s what operators are for.

Although many will feel familiar from school math, PHP includes some syntactic sugar specifically designed to solve common web development problems.

Arithmetic operators (the classics)

We won’t dwell too much on this, but there are a couple of important details.

OperatorNameExampleResult
+Addition$a + $bSum of values
-Subtraction$a - $bDifference
*Multiplication$a * $bProduct
/Division$a / $bQuotient (note: may return float)
%Modulus$a % $bThe remainder of division (ideal for checking if a number is even/odd)
**Exponentiation$a ** $bPower (modern approach; previously we used pow())

Typing note: division / returns an integer when both operands are integers and the division is exact. In all other cases it returns a float; it does not depend on a configuration option.

Logical operators

They are used to make complex decisions by combining conditions.

  • AND (&&): Both conditions must be true.
  • OR (||): At least one must be true.
  • NOT (!): Inverts the value (!true is false).

The trap: && vs and

You will notice PHP allows writing and and or (full words). Advice: normally use the symbols && and ||.

The reason is precedence (the order in which things are resolved). and has very low priority and can cause silent bugs in assignments. Save yourself the headache: use symbols.

The null coalescing operator (??)

This operator is possibly the best quality-of-life improvement PHP has ever had.

In web development, it’s very common to receive data that maybe exists or maybe doesn’t (for example, an optional parameter in a URL).

The old way (The horror of isset):

// Before PHP 7
$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';
Copied!

We had to repeat the variable. It was verbose and ugly.

The modern way (??):

// Now
$name = $_GET['name'] ?? 'Guest';
Copied!

What does it do? It returns the first operand if it exists and is not null. Otherwise, it returns the second. It’s elegant, clean, and straightforward.

Bonus: null coalescing assignment (??=)

Since PHP 7.4, we can make it even shorter if we want to assign a default value to a variable only if it doesn’t have one:

$config['language'] ??= 'en'; 
// If $config['language'] doesn't exist, assign 'en'. If it already exists, leave it alone.
Copied!

The spaceship operator (<=>)

Introduced in PHP 7, its official name is the Spaceship Operator. This operator solves a very specific problem: sorting things.

When we compare two values ($a and $b) to sort them, we need to know three things:

  1. Is $a less than $b?
  2. Are they equal?
  3. Is $a greater than $b?

The <=> operator asks all three questions at once and returns a number:

  • Returns an integer less than 0 if $a < $b
  • Returns 0 if $a == $b
  • Returns an integer greater than 0 if $a > $b

What is this used for? For writing one-line custom sort functions (usort).

// Sort a list of numbers from smallest to largest
$numbers = [10, 5, 20, 2];

usort($numbers, fn($a, $b) => $a <=> $b);

// Result: [2, 5, 10, 20]
Copied!

Without the spaceship, that sort function would take 4 or 5 lines of if/else.

Comparison operators

Finally, a warning about comparing values.

  • == (Weak equality): PHP will try to convert types. '5' == 5 is true. Avoid it.
  • === (Identity): Compares value AND type. '5' === 5 is false. Always use it.
  • != vs !==: The same applies for “not equal”. Always use the strict version !==.