Skip to main content

PHP Operators

Operators are symbols that perform operations on values and variables.

Example:

$a = 5 + 5;

Here:

+

is an operator.


Types of Operators

PHP provides many operators:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Increment / Decrement Operators
  6. String Operators
  7. Array Operators
  8. Null Operators
  9. Bitwise Operators

Arithmetic Operators

OperatorMeaningExample
+Addition$a + $b
-Subtraction$a - $b
*Multiplication$a * $b
/Division$a / $b
%Modulus$a % $b
**Power$a ** $b

Addition

echo 10 + 5;

Output:

15

Subtraction

echo 10 - 5;

Output:

5

Multiplication

echo 10 * 5;

Output:

50

Division

echo 10 / 5;

Output:

2

Modulus

Returns remainder.

echo 10 % 3;

Output:

1

Power

echo 2 ** 3;

Output:

8

Assignment Operators

OperatorExample
=$a = 5
+=$a += 5
-=$a -= 5
*=$a *= 5
/=$a /= 5
%=$a %= 5
.=$text .= "Hello"

Example:

$a = 10;

$a += 5;

echo $a;

Output:

15

Comparison Operators

OperatorMeaning
==Equal
===Identical
!=Not Equal
!==Not Identical
>Greater Than
<Less Than
>=Greater Than Equal
<=Less Than Equal
<=>Spaceship Operator

Equal

5 == "5";

Returns:

true

Identical

5 === "5";

Returns:

false

Spaceship Operator

echo 1 <=> 2;

Output:

-1
echo 2 <=> 2;

Output:

0
echo 3 <=> 2;

Output:

1

Logical Operators

OperatorMeaning
&&AND
`
!NOT
andAND
orOR
xorXOR

AND

if ($online && $staff) {

}

OR

if ($admin || $owner) {

}

NOT

if (!$banned) {

}

Increment Operators

$a++;

Decrement Operators

$a--;

Pre Increment

++$a;

Post Increment

$a++;

Difference:

$a = 5;

echo ++$a;

Output:

6

$a = 5;

echo $a++;

Output:

5

String Operators

Concatenation

echo "Hello " . "World";

Concatenation Assignment

$text = "Hello";

$text .= " World";

Array Operators

OperatorMeaning
+Union
==Equal
===Identical

Example:

$a = [
"name" => "Aayan"
];

$b = [
"rank" => "Owner"
];

$c = $a + $b;

Null Coalescing Operator

$name =
$_GET["name"] ?? "Guest";

Null Safe Operator (PHP 8)

$user?->getProfile()?->getName();

Ternary Operator

$status =
$online
? "Online"
: "Offline";

Bitwise Operators

OperatorMeaning
&AND
``
^XOR
~NOT
<<Left Shift
>>Right Shift

Operator Precedence

echo 5 + 5 * 2;

Output:

15

because:

5 + (5 * 2)

Using Parentheses

echo (5 + 5) * 2;

Output:

20

PocketMine Examples

Permission Check:

if (
$sender->hasPermission(
"zyro.admin"
) &&
$sender instanceof Player
) {

}

Economy:

$money += 1000;

Chat:

$message .= "!";

Exercises

  1. Add two numbers.
  2. Check if player is staff.
  3. Use ternary operator.
  4. Practice spaceship operator.

Quiz

Which operator concatenates strings?
.

Which operator checks identical values?
===

Which operator provides default values?
??

References

https://www.php.net/manual/en/language.operators.php


Next Chapter

➡ PHP Conditions