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:
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Increment / Decrement Operators
- String Operators
- Array Operators
- Null Operators
- Bitwise Operators
Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | 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
| Operator | Example |
|---|---|
= | $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
| Operator | Meaning |
|---|---|
== | 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
| Operator | Meaning |
|---|---|
&& | AND |
| ` | |
! | NOT |
and | AND |
or | OR |
xor | XOR |
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
| Operator | Meaning |
|---|---|
+ | 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
| Operator | Meaning |
|---|---|
& | 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
- Add two numbers.
- Check if player is staff.
- Use ternary operator.
- 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