About Lesson
What are operators in PHP?
Operators are used to perform operations on variables and values. PHP supports many types of operators.
✅ Types of Operators
Type | Example Symbols |
---|---|
Arithmetic | + , - , * , / , % |
Assignment | = , += , -= , *= , /= , .= |
Comparison | == , === , != , <> , !== , < , > , <= , >= |
Increment/Decrement | ++ , -- |
Logical | && , ` |
String | . , .= |
Array | + , == , === , != , <> , !== |
Conditional (Ternary) | ?: |
Null coalescing | ?? |
🔢 1. Arithmetic Operators
Used for mathematical operations.
Operator | Description | Example |
---|---|---|
+ | Addition | $x + $y |
- | Subtraction | $x - $y |
* | Multiplication | $x * $y |
/ | Division | $x / $y |
% | Modulus (Remainder) | $x % $y |
Example:
PHP
<?php
$x = 10;
$y = 3;
echo $x + $y; // Output: 13
?>
🟩 2. Assignment Operators
Used to assign values to variables.
Operator | Example | Same as |
---|---|---|
= | $x = 5 | $x = 5 |
+= | $x += 5 | $x = $x + 5 |
-= | $x -= 5 | $x = $x - 5 |
*= | $x *= 5 | $x = $x * 5 |
/= | $x /= 5 | $x = $x / 5 |
.= | $x .= "test" | $x = $x . "test" |
⚖️ 3. Comparison Operators
Used to compare values.
Operator | Description | Example |
---|---|---|
== | Equal | $x == $y |
=== | Identical (value and type) | $x === $y |
!= | Not equal | $x != $y |
<> | Not equal | $x <> $y |
!== | Not identical | $x !== $y |
> | Greater than | $x > $y |
< | Less than | $x < $y |
>= | Greater than or equal | $x >= $y |
<= | Less than or equal | $x <= $y |
➕➖ 4. Increment/Decrement Operators
Operator | Description | Example |
---|---|---|
++$x | Pre-increment | Increases by 1, then returns |
$x++ | Post-increment | Returns, then increases by 1 |
--$x | Pre-decrement | Decreases by 1, then returns |
$x-- | Post-decrement | Returns, then decreases by 1 |
⚙️ 5. Logical Operators
Used for conditional logic.
Operator | Description | Example |
---|---|---|
and | True if both are true | $x and $y |
or | True if at least one is true | $x or $y |
xor | True if only one is true | $x xor $y |
&& | And (high precedence) | $x && $y |
` | ` | |
! | Not | !$x |
🔗 6. String Operators
Operator | Description | Example |
---|---|---|
. | Concatenation | "Hello" . "World" |
.= | Concatenate then assign | $x .= "World" |
🧮 7. Array Operators
Operator | Description |
---|---|
+ | Union of two arrays |
== | Equal arrays (same key-value pairs) |
=== | Identical (also same order and type) |
!= / <> | Not equal |
!== | Not identical |
❓ 8. Conditional (Ternary) Operator
Shorthand for if...else
.
Syntax:
PHP
(condition) ? value_if_true : value_if_false;
(condition) ? value_if_true : value_if_false;
PHP
<?php
$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
?>
⚡ 9. Null Coalescing Operator (??
)
Used to return the first defined value.
Example:
PHP
<?php
$username = $_GET['user'] ?? "Guest";
echo $username;
?>