PHP Operators
What Are Operators in PHP?
Operators are symbols used to perform operations on variables and values. PHP supports various types of operators.
Types of PHP Operators
1️⃣ Arithmetic Operators (Used for mathematical operations)
Operator |
Description |
Example ($a = 10, $b = 5 ) |
Result |
+ |
Addition |
$a + $b |
15 |
- |
Subtraction |
$a - $b |
5 |
* |
Multiplication |
$a * $b |
50 |
/ |
Division |
$a / $b |
2 |
% |
Modulus |
$a % $b |
0 |
2️⃣ Assignment Operators (Used to assign values)
Operator |
Description |
Example ($a = 10 ) |
Equivalent To |
= |
Assign |
$a = 10 |
$a = 10 |
+= |
Add and assign |
$a += 5 |
$a = $a + 5 |
-= |
Subtract and assign |
$a -= 3 |
$a = $a - 3 |
*= |
Multiply and assign |
$a *= 2 |
$a = $a * 2 |
/= |
Divide and assign |
$a /= 2 |
$a = $a / 2 |
3️⃣ Comparison Operators (Used for value comparison)
Operator |
Description |
Example ($a = 10, $b = 5 ) |
Result |
== |
Equal |
$a == $b |
false |
!= |
Not equal |
$a != $b |
true |
> |
Greater than |
$a > $b |
true |
< |
Less than |
$a < $b |
false |
>= |
Greater than or equal |
$a >= $b |
true |
<= |
Less than or equal |
$a <= $b |
false |
4️⃣ Logical Operators (Used for logical operations)
Operator |
Description |
Example ($x = true, $y = false ) |
Result |
&& |
AND |
$x && $y |
false |
` |
|
` |
OR |
! |
NOT |
!$x |
false |
5️⃣ Increment & Decrement Operators (Used to increase or decrease values)
Operator |
Description |
Example ($a = 5 ) |
Result |
++$a |
Pre-increment |
++$a |
6 |
$a++ |
Post-increment |
$a++ |
5 (then becomes 6) |
--$a |
Pre-decrement |
--$a |
4 |
$a-- |
Post-decrement |
$a-- |
5 (then becomes 4) |
6️⃣ String Operators (Used to manipulate strings)
Operator |
Description |
Example ($a = "Hello" , $b = " World" ) |
Result |
. |
Concatenation |
$a . $b |
"Hello World" |
.= |
Concatenation & Assign |
$a .= $b |
$a = "Hello World" |
Conclusion
✔ PHP operators help perform calculations, assignments, comparisons, and logical operations.
✔ Arithmetic, comparison, and logical operators are commonly used in PHP programs.
✔ String operators allow concatenation.
✔ Understanding operators is essential for efficient coding in PHP.