PHP Operators Explained
PHP operators are special symbols used to perform operations on variables and values. Whether you’re adding numbers, comparing values, checking conditions, or joining strings, operators are used in almost every PHP program.
If variables are the containers that store data, then operators are the tools that manipulate that data.
In this tutorial, you’ll learn the different types of PHP operators with easy-to-understand examples.
What is an Operator?
An operator is a symbol that tells PHP to perform a specific action.
Example:
<?php
$a = 10;
$b = 5;
echo $a + $b;
?>
Output
15
Here:
$aand$bare operands.+is the operator.- The result is
15.
Why Are Operators Important?
Operators help you:
- Perform calculations
- Compare values
- Make decisions
- Build conditions
- Manipulate strings
- Work with arrays
Without operators, programming would not be possible.
Types of PHP Operators
PHP provides several categories of operators:
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Increment & Decrement Operators
- Logical Operators
- String Operators
- Array Operators
- Conditional (Ternary) Operator
- Null Coalescing Operator
Let’s explore them one by one.
1. Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Description | Example |
|---|---|---|
+ | Addition | $a + $b |
- | Subtraction | $a - $b |
* | Multiplication | $a * $b |
/ | Division | $a / $b |
% | Modulus | $a % $b |
** | Exponent | $a ** 2 |
Example:
<?php
$a = 20;
$b = 4;
echo $a + $b;
echo "<br>";
echo $a - $b;
echo "<br>";
echo $a * $b;
echo "<br>";
echo $a / $b;
?>
Output:
24
16
80
5
2. Assignment Operators
Assignment operators assign values to variables.
Basic assignment:
<?php
$age = 25;
?>
Compound assignment:
<?php
$x = 10;
$x += 5;
echo $x;
?>
Output:
15
Other assignment operators include:
-=*=/=%=
These operators make your code shorter and easier to read.
3. Comparison Operators
Comparison operators compare two values and return either true or false.
Example:
<?php
$a = 10;
$b = 20;
var_dump($a < $b);
?>
Output:
bool(true)
Common comparison operators:
==Equal===Identical!=Not Equal!==Not Identical>Greater Than<Less Than>=Greater Than or Equal To<=Less Than or Equal To
Comparison operators are widely used in if statements and loops.
4. Increment and Decrement Operators
These operators increase or decrease a variable by one.
Increment:
<?php
$count = 5;
$count++;
echo $count;
?>
Output:
6
Decrement:
<?php
$count = 5;
$count--;
echo $count;
?>
Output:
4
These operators are commonly used in loops and counters.
5. Logical Operators
Logical operators combine multiple conditions.
Example:
<?php
$age = 22;
$citizen = true;
if($age >= 18 && $citizen){
echo "Eligible to Vote";
}
?>
Common logical operators:
&&AND||OR!NOT
Logical operators are essential for decision-making in PHP applications.