PHP Operators – Complete Beginner Tutorial
Operators are symbols that tell PHP to perform an action. They allow you to add numbers, compare values, join strings, make decisions, and perform calculations. Every PHP application, from a simple contact form to a complete e-commerce website, relies heavily on operators.
What is an Operator?
An operator performs an operation on one or more values called operands.
Example:
<?php
$a = 10;
$b = 5;
echo $a + $b;
?>
Output:
15
Here, + is the operator, while $a and $b are operands.
Main Types of PHP Operators
| Operator Type | Purpose |
|---|---|
| Arithmetic | Mathematical calculations |
| Assignment | Assign values to variables |
| Comparison | Compare two values |
| Logical | Combine conditions |
| Increment / Decrement | Increase or decrease values |
| String | Join text together |
| Array | Compare arrays |
| Conditional | Short decision making |
Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Description | Example |
|---|---|---|
| + | Addition | $a + $b |
| – | Subtraction | $a – $b |
| * | Multiplication | $a * $b |
| / | Division | $a / $b |
| % | Modulus (Remainder) | $a % $b |
| ** | Exponent | $a ** 2 |
Addition Example
<?php
$price = 250;
$tax = 50;
$total = $price + $tax;
echo $total;
?>
Output:
300
Subtraction Example
<?php
$available = 50;
$booked = 12;
echo $available - $booked;
?>
Output:
38
Multiplication Example
<?php
$price = 120;
$nights = 4;
echo $price * $nights;
?>
Output:
480
Division Example
<?php
$total = 1000;
$people = 4;
echo $total / $people;
?>
Output:
250
Modulus Operator (%)
The modulus operator returns the remainder after division.
<?php
echo 10 % 3;
?>
Output:
1
It is commonly used to determine whether a number is even or odd.
<?php
$number = 12;
if($number % 2 == 0)
{
echo "Even Number";
}
else
{
echo "Odd Number";
}
?>
Exponent Operator (**)
The exponent operator raises a number to a power.
<?php
echo 5 ** 2;
?>
Output:
25
Assignment Operator (=)
The assignment operator stores a value inside a variable.
<?php
$name = "John";
echo $name;
?>
Remember: The assignment operator (=) stores a value, while comparison operators such as == and === compare values. This is a common source of mistakes for beginners.
Compound Assignment Operators
Compound assignment operators provide a shorter way to update a variable. Instead of writing the variable name twice, PHP lets you combine the operation with the assignment.
| Operator | Equivalent To | Description |
|---|---|---|
| += | $a = $a + $b | Add and assign |
| -= | $a = $a – $b | Subtract and assign |
| *= | $a = $a * $b | Multiply and assign |
| /= | $a = $a / $b | Divide and assign |
| %= | $a = $a % $b | Modulus and assign |
| .= | $text = $text . $newText | Append string |
Example:
<?php
$total = 100;
$total += 50;
echo $total;
?>
Output:
150
Comparison Operators
Comparison operators compare two values and return either true or false.
| Operator | Description |
|---|---|
| == | Equal value |
| === | Equal value and type |
| != | Not equal |
| !== | Not equal value or type |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
| <=> | Spaceship operator |
Example:
<?php
$age = 25;
if($age >= 18)
{
echo "Adult";
}
?>
Logical Operators
Logical operators combine multiple conditions.
| Operator | Description |
|---|---|
| && | AND |
| || | OR |
| ! | NOT |
| xor | Exclusive OR |
Example:
<?php
$isLoggedIn = true;
$isAdmin = true;
if($isLoggedIn && $isAdmin)
{
echo "Administrator Panel";
}
?>
String Operators
PHP provides operators specifically for strings.
Concatenation Operator (.)
<?php
$first = "Travel";
$second = " Culture";
echo $first . $second;
?>
Output:
Travel Culture
Concatenation Assignment (.=)
<?php
$text = "Hello";
$text .= " World";
echo $text;
?>
Output:
Hello World
Increment and Decrement Operators
These operators increase or decrease a number by one.
<?php
$count = 5;
$count++;
echo $count;
?>
Output:
6
Similarly:
$count--;
decreases the value by one.
Null Coalescing Operator (??)
The null coalescing operator returns the first value that exists and is not NULL.
<?php
$username = $_GET['user'] ?? "Guest";
echo $username;
?>
If no user parameter exists, the output will be:
Guest
Ternary Operator
The ternary operator provides a short way to write simple if…else statements.
<?php
$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
?>
Output:
Adult
Spaceship Operator (<=>)
The spaceship operator compares two expressions.
<?php
echo 5 <=> 10;
?>
Possible results:
- -1 if the left value is smaller
- 0 if both values are equal
- 1 if the left value is greater
Real-World Example
Suppose you are calculating the total cost of a hotel booking.
<?php
$pricePerNight = 150;
$nights = 4;
$total = $pricePerNight * $nights;
if($nights >= 7)
{
$total *= 0.90;
}
echo $total;
?>
This example combines arithmetic, assignment, and comparison operators to calculate a booking total with a discount for longer stays.
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Using = instead of == | Use == or === for comparisons. |
| Using == when === is needed | Prefer strict comparisons for reliability. |
| Forgetting operator precedence | Use parentheses to make expressions clear. |
| Joining strings with + | Use the . operator for concatenation. |
Best Practices
- Use === whenever strict comparison is appropriate.
- Use parentheses to improve readability.
- Keep expressions simple and easy to understand.
- Avoid deeply nested ternary operators.
- Choose descriptive variable names.
- Test complex conditions carefully.
Practice Exercises
- Calculate the total price of five products.
- Determine whether a visitor is eligible for a discount.
- Use the concatenation operator to build a welcome message.
- Create an age checker using the ternary operator.
- Use the null coalescing operator to provide a default value.
- Write a program that determines whether a number is even or odd using the modulus operator.
Summary
Operators allow PHP programs to perform calculations, compare values, combine conditions, manipulate text, and make decisions. Mastering arithmetic, comparison, logical, string, assignment, and conditional operators is essential because they are used in almost every PHP application.
Frequently Asked Questions
What is the difference between = and ==?
The = operator assigns a value to a variable, while == compares two values.
Why should I use === instead of ==?
The === operator compares both the value and the data type, making comparisons more predictable.
How do I join two strings in PHP?
Use the concatenation operator (.) rather than the plus sign.
What does the modulus operator (%) do?
It returns the remainder after division and is often used to determine whether a number is even or odd.
What is the ternary operator used for?
It provides a concise way to write simple if…else statements.
Quick Challenge
Create a PHP program that calculates the total cost of a tour booking. Store the tour price, number of travellers, and any discount percentage in variables. Use arithmetic operators to calculate the final amount and display whether the booking qualifies for a group discount.
Next Tutorial
Now that you understand PHP operators, it’s time to make decisions in your code using If, Else, and Elseif Statements.
Next: PHP If…Else Statements