Operators in PHP are symbols used to perform operations on variables and values. They are essential for performing arithmetic calculations, comparisons, logical operations, and more. Understanding PHP operators is crucial for writing efficient and functional scripts.
Types of PHP Operators
1. Arithmetic Operators
Used to perform mathematical calculations.
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition | $a + $b | Sum |
- | Subtraction | $a - $b | Difference |
* | Multiplication | $a * $b | Product |
/ | Division | $a / $b | Quotient |
% | Modulus | $a % $b | Remainder |
** | Exponentiation | $a ** $b | Power |
Example:
<?php
$a = 10;
$b = 3;
echo $a + $b; // 13
echo $a % $b; // 1
?>
2. Assignment Operators
Used to assign values to variables.
| Operator | Description | Example |
|---|---|---|
= | Simple assignment | $a = 5; |
+= | Add and assign | $a += 3; |
-= | Subtract and assign | $a -= 2; |
*= | Multiply and assign | $a *= 2; |
/= | Divide and assign | $a /= 2; |
%= | Modulus and assign | $a %= 3; |
3. Comparison Operators
Used to compare two values.
| Operator | Description | Example |
|---|---|---|
== | Equal | $a == $b |
=== | Identical (value & type) | $a === $b |
!= | Not equal | $a != $b |
!== | Not identical | $a !== $b |
> | Greater than | $a > $b |
< | Less than | $a < $b |
>= | Greater or equal | $a >= $b |
<= | Less or equal | $a <= $b |
Example:
<?php
$a = 5;
$b = 10;
if ($a < $b) {
echo "$a is less than $b";
}
?>
4. Logical Operators
Used to combine conditional statements.
| Operator | Description | Example |
|---|---|---|
&& | And | $a && $b |
| ` | ` | |
! | Not | !$a |
and | And (lower precedence) | $a and $b |
or | Or (lower precedence) | $a or $b |
5. Increment / Decrement Operators
Used to increase or decrease variable values by 1.
<?php
$a = 5;
$a++; // Increment, now 6
$a--; // Decrement, now 5
?>
6. String Operators
Used to work with strings.
| Operator | Description | Example |
|---|---|---|
. | Concatenation | $a . $b |
.= | Concatenate and assign | $a .= $b |
Example:
<?php
$greet = "Hello";
$greet .= " World!";
echo $greet; // Outputs: Hello World!
?>
7. Array Operators
Used to compare arrays or combine them.
| Operator | Description |
|---|---|
+ | Union of arrays |
== | Equality |
=== | Identity (equal & same order) |
!= | Not equal |
!== | Not identical |
Best Practices
- Use the correct operator type for your operation to avoid unexpected results.
- Be careful with comparison operators, especially
==vs===. - Use parentheses
()to ensure order of operations is correct in complex expressions. - Combine logical operators carefully to avoid logical errors in conditions.
External Reference: PHP Manual
View Other Articles About PHP: Learn PHP Articles