Paramclasses Academy - Blog

Tutorials Details

PHP Operators With Practical Examples

PHP Operators With Practical Examples

October 9, 2026

Meta Title: Core PHP Module 3: PHP Operators With Examples

Meta Description: Learn PHP operators for beginners, including arithmetic, assignment, comparison, logical, increment, decrement, and ternary operators with practical examples.

Focus Keyword: PHP Operators Tutorial for Beginners

Secondary Keywords: PHP Arithmetic Operators, PHP Assignment Operators, PHP Comparison Operators, PHP Logical Operators, PHP Increment and Decrement Operators, PHP Ternary Operator, Core PHP Tutorial, PHP Practical Examples

Suggested URL Slug: core-php-module-3-php-operators

Introduction to PHP Operators

Welcome to Module 3 of our Core PHP Programming Tutorial for Beginners.

In Module 1, we learned what PHP is, how it works, and how to run a PHP program using XAMPP. In Module 2, we covered variables, constants, data types, comments, echo, and print.

In this module, we will learn about PHP operators, which are used to perform calculations, compare values, assign data, and make decisions in a program.

Operators are essential for developing dynamic websites, billing systems, login applications, e-commerce websites, school management software, and other PHP-based web applications.

For example, when an online shopping website calculates the total price of products, applies discounts, or checks whether a customer is eligible for free delivery, PHP operators can help perform these operations.

Let's understand each type of PHP operator with simple explanations, code examples, outputs, and real-world applications.

1. What Are Operators in PHP?

Operators are symbols or keywords that perform operations on values and variables.

For example:

<?php
$a = 10;
$b = 5;

echo $a + $b;
?>

Output:

15

Explanation

  • $a stores the value 10.

  • $b stores the value 5.

  • + is the addition operator.

  • echo displays the result.

Here, PHP adds the two values and displays 15.

Why Do We Use PHP Operators?

PHP operators are used for:

  1. Performing mathematical calculations.

  2. Assigning values to variables.

  3. Comparing two values.

  4. Combining multiple conditions.

  5. Increasing or decreasing variable values.

  6. Making decisions using conditional expressions.

  7. Calculating product prices, discounts, taxes, totals, and balances.

PHP provides several categories of operators. Let's explore them one by one.

2. Arithmetic Operators in PHP

Arithmetic operators perform mathematical calculations such as addition, subtraction, multiplication, division, and finding the remainder.

Types of Arithmetic Operators

Operator Name Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Modulus 10 % 3 1
** Exponentiation 2 ** 3 8

Example 1: Basic Arithmetic Operations

<?php
$a = 20;
$b = 10;

echo "Addition: " . ($a + $b) . "<br>";
echo "Subtraction: " . ($a - $b) . "<br>";
echo "Multiplication: " . ($a * $b) . "<br>";
echo "Division: " . ($a / $b) . "<br>";
echo "Remainder: " . ($a % 3) . "<br>";
echo "Power: " . ($a ** 2);
?>

Output:

Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Remainder: 2
Power: 400

Explanation

  • + adds two values.

  • - subtracts one value from another.

  • * multiplies two values.

  • / divides one value by another.

  • % returns the remainder after division.

  • ** calculates a power.

Remember that division by zero is invalid and should be handled appropriately in your application.

Real-World Example: Shopping Bill

Suppose a customer purchases two products from an online store.

  • Product price: ₹500

  • Quantity: 2

  • Delivery charge: ₹50

<?php
$productPrice = 500;
$quantity = 2;
$deliveryCharge = 50;

$subtotal = $productPrice * $quantity;
$total = $subtotal + $deliveryCharge;

echo "<h2>Shopping Bill</h2>";
echo "Product Price: ₹" . $productPrice . "<br>";
echo "Quantity: " . $quantity . "<br>";
echo "Subtotal: ₹" . $subtotal . "<br>";
echo "Delivery Charge: ₹" . $deliveryCharge . "<br>";
echo "Total Amount: ₹" . $total;
?>

Output:

Shopping Bill
Product Price: ₹500
Quantity: 2
Subtotal: ₹1000
Delivery Charge: ₹50
Total Amount: ₹1050

Real-world application: Arithmetic operators are used in billing software, shopping carts, invoice generation, salary calculations, and inventory management.

For production billing applications, use an appropriate decimal or integer-based money representation to avoid floating-point precision problems.

3. Assignment Operators in PHP

Assignment operators are used to assign values to variables.

The most common assignment operator is =.

Types of Assignment Operators

Operator Example Equivalent Operation
= $a = 10 Assigns 10 to $a
+= $a += 5 $a = $a + 5
-= $a -= 5 $a = $a - 5
*= $a *= 2 $a = $a * 2
/= $a /= 2 $a = $a / 2
%= $a %= 3 $a = $a % 3
.= $name .= " PHP" Appends text to a string

Example 1: Using Assignment Operators

<?php
$total = 100;

$total += 50;
echo "After Addition: " . $total . "<br>";

$total -= 20;
echo "After Subtraction: " . $total . "<br>";

$total *= 2;
echo "After Multiplication: " . $total . "<br>";

$total /= 2;
echo "After Division: " . $total;
?>

Output:

After Addition: 150
After Subtraction: 130
After Multiplication: 260
After Division: 130

Explanation

Initially, $total is 100.

  • $total += 50 increases the total to 150.

  • $total -= 20 decreases it to 130.

  • $total *= 2 changes it to 260.

  • $total /= 2 changes it back to 130.

Example 2: String Assignment Operator

<?php
$message = "Welcome";
$message .= " to PHP";

echo $message;
?>

Output:

Welcome to PHP

The .= operator appends text to an existing string.

Real-World Example: Wallet Balance

<?php
$balance = 1000;

// Add money
$balance += 500;

// Deduct a purchase
$balance -= 200;

echo "Available Balance: ₹" . $balance;
?>

Output:

Available Balance: ₹1300

Real-world application: Assignment operators can simplify calculations involving shopping cart totals, inventory quantities, counters, and running balances.

A real financial application must also validate transactions and update balances securely in the database.

4. Comparison Operators in PHP

Comparison operators compare two values and produce a boolean result: true or false.

They are commonly used in if statements, login systems, validation, search filters, and eligibility checks.

Types of Comparison Operators

Operator Meaning Example
== Equal in value after type conversion when applicable 5 == "5"
=== Equal in value and type 5 === 5
!= Not equal in value 5 != 3
!== Not identical in value or type 5 !== "5"
> Greater than 10 > 5
< Less than 5 < 10
>= Greater than or equal to 10 >= 10
<= Less than or equal to 5 <= 10
<=> Spaceship comparison 5 <=> 10

The spaceship operator <=> returns -1 when the left value is smaller, 0 when the values compare equal, and 1 when the left value is greater.

Example 1: Comparison Operations

<?php
$a = 10;
$b = 5;

var_dump($a > $b);
echo "<br>";

var_dump($a < $b);
echo "<br>";

var_dump($a == 10);
echo "<br>";

var_dump($a === "10");
?>

Output:

bool(true)
bool(false)
bool(true)
bool(false)

Explanation

  • $a > $b is true because 10 is greater than 5.

  • $a < $b is false because 10 is not less than 5.

  • $a == 10 is true because the values are equal.

  • $a === "10" is false because the first value is an integer and the second is a string.

Important: The === operator checks both value and type. It is often a safer choice when you need to avoid unexpected type conversions.

Real-World Example: Student Result

<?php
$marks = 75;
$passingMarks = 33;

if ($marks >= $passingMarks) {
    echo "Student has passed.";
} else {
    echo "Student has failed.";
}
?>

Output:

Student has passed.

Real-world application: Comparison operators are useful for checking passing marks, product stock, minimum order values, membership levels, and account status.

5. Logical Operators in PHP

Logical operators combine conditions or reverse a condition.

They are especially useful when a program must check multiple requirements at the same time.

Types of Logical Operators

Operator Meaning Example
&& Logical AND $age >= 18 && $hasId
`   `
! Logical NOT !$isLoggedIn
and Logical AND $a and $b
or Logical OR $a or $b
xor True when exactly one operand is true $a xor $b

The words and and or have different operator precedence from && and ||. Beginners can usually use && and || with parentheses to make conditions clear.

Example 1: AND Operator

<?php
$age = 25;
$hasLicense = true;

if ($age >= 18 && $hasLicense) {
    echo "Eligible to drive.";
} else {
    echo "Not eligible to drive.";
}
?>

Output:

Eligible to drive.

Both conditions must be true for the message to display.

Example 2: OR Operator

<?php
$isAdmin = false;
$isManager = true;

if ($isAdmin || $isManager) {
    echo "Access granted.";
} else {
    echo "Access denied.";
}
?>

Output:

Access granted.

Only one condition needs to be true for the OR expression to succeed.

Example 3: NOT Operator

<?php
$isLoggedIn = false;

if (!$isLoggedIn) {
    echo "Please log in first.";
}
?>

Output:

Please log in first.

The ! operator reverses the boolean value.

Real-World Example: Free Delivery Eligibility

Suppose an online store offers free delivery when an order reaches ₹1,000 and the customer belongs to its membership program.

<?php
$orderAmount = 1200;
$isMember = true;

if ($orderAmount >= 1000 && $isMember) {
    echo "Congratulations! You qualify for free delivery.";
} else {
    echo "Standard delivery charges apply.";
}
?>

Output:

Congratulations! You qualify for free delivery.

Real-world application: Logical operators are used for checking eligibility, validating forms, applying offers, controlling access, and enforcing business rules.

6. Increment and Decrement Operators in PHP

Increment operators increase a variable's value by one. Decrement operators decrease a variable's value by one.

They are useful for counters, quantities, sequence numbers, and loop operations.

Types of Increment and Decrement Operators

Operator Meaning
++$a Pre-increment
$a++ Post-increment
--$a Pre-decrement
$a-- Post-decrement

The difference between pre-increment and post-increment is when the updated value is used in an expression.

Example 1: Pre-Increment

<?php
$a = 10;

echo ++$a;
?>

Output:

11

The value increases first, then PHP uses the updated value.

Example 2: Post-Increment

<?php
$a = 10;

echo $a++;
echo "<br>";
echo $a;
?>

Output:

10
11

The first statement outputs the original value. Afterward, the variable increases to 11.

Example 3: Decrement

<?php
$quantity = 5;

--$quantity;

echo $quantity;
?>

Output:

4

Real-World Example: Product Stock

<?php
$stock = 10;

// One product is sold
$stock--;

echo "Remaining Stock: " . $stock;
?>

Output:

Remaining Stock: 9

Real-world application: Increment and decrement operators can be used for simple counters and quantity calculations. In real inventory systems, stock updates must be validated and handled safely to prevent incorrect stock levels when multiple users make purchases simultaneously.

7. Ternary Operator in PHP

The ternary operator is a short way to choose between two expressions based on a condition.

It is an alternative to a simple if-else statement.

Syntax

condition ? value_if_true : value_if_false;

Example 1: Check Voting Eligibility

<?php
$age = 20;

$message = ($age >= 18)
    ? "Eligible to vote."
    : "Not eligible to vote.";

echo $message;
?>

Output:

Eligible to vote.

Explanation

  • If $age >= 18 is true, the first message is selected.

  • Otherwise, the second message is selected.

  • The selected value is stored in $message.

Example 2: Check Student Result

<?php
$marks = 28;

$result = ($marks >= 33) ? "Pass" : "Fail";

echo $result;
?>

Output:

Fail

Real-World Example: Product Availability

<?php
$stock = 5;

$status = ($stock > 0) ? "In Stock" : "Out of Stock";

echo "Product Status: " . $status;
?>

Output:

Product Status: In Stock

Real-world application: The ternary operator is useful for selecting short messages, displaying product status, showing simple labels, and choosing between two values.

For complicated business logic, a regular if-else statement is often easier to read and maintain.

8. String Operators in PHP

PHP provides operators for joining strings together.

The two commonly used string operators are:

  • . — Concatenation

  • .= — Concatenation assignment

Example 1: Concatenation Operator

<?php
$firstName = "Rahul";
$lastName = "Sharma";

$fullName = $firstName . " " . $lastName;

echo $fullName;
?>

Output:

Rahul Sharma

The dot operator joins the first name, a space, and the last name.

Example 2: Concatenation Assignment

<?php
$message = "Welcome";
$message .= " to Core PHP";

echo $message;
?>

Output:

Welcome to Core PHP

Real-World Example: Welcome Message

<?php
$customerName = "Rahul";

$message = "Hello, " . $customerName . "! Welcome back.";

echo $message;
?>

Output:

Hello, Rahul! Welcome back.

Real-world application: String operators help create welcome messages, product descriptions, email content, reports, and dynamic text.

When inserting untrusted text into HTML, escape the value appropriately using htmlspecialchars().

9. Operator Precedence in PHP

Operator precedence determines which operations are performed first when an expression contains multiple operators.

For example:

<?php
$result = 10 + 5 * 2;

echo $result;
?>

Output:

20

Multiplication is performed before addition, so the expression is evaluated as 10 + (5 * 2).

Using Parentheses

You can use parentheses to make the intended order explicit.

<?php
$result = (10 + 5) * 2;

echo $result;
?>

Output:

30

In this example, PHP evaluates the expression inside the parentheses first.

Best practice: Use parentheses in complex expressions to make calculations and conditions easier to understand.

10. Combined Practical Example: Student Marks Calculator

Let's combine arithmetic, assignment, comparison, and ternary operators in one program.

Create a file named student_result.php.

<?php
// Student details
$studentName = "Rahul Sharma";
$maths = 80;
$science = 75;
$english = 85;

// Calculate total and percentage
$total = $maths + $science + $english;
$percentage = $total / 3;

// Check result
$passingMarks = 33;

$passed = (
    $maths >= $passingMarks &&
    $science >= $passingMarks &&
    $english >= $passingMarks
);

$result = $passed ? "Pass" : "Fail";

// Display report
echo "<h2>Student Result</h2>";
echo "Name: " . $studentName . "<br>";
echo "Total Marks: " . $total . " / 300<br>";
echo "Percentage: " . $percentage . "%<br>";
echo "Result: " . $result;
?>

Expected Output

Student Result

Name: Rahul Sharma
Total Marks: 240 / 300
Percentage: 80%
Result: Pass

Explanation

  • Arithmetic operators calculate the total and percentage.

  • Comparison operators check each subject's marks.

  • The logical AND operator verifies that all subjects meet the passing requirement.

  • The ternary operator selects the final result.

  • echo displays the report.

This example demonstrates how operators work together in a practical PHP program.

11. Combined Real-World Example: Discount Calculator

Let's create a basic shopping discount calculator.

Suppose a customer purchases products worth ₹2,000 and receives a 10% discount when the order value is at least ₹1,500.

<?php
// Order details
$orderAmount = 2000;
$discountRate = 10;

// Calculate discount eligibility
$eligible = ($orderAmount >= 1500);

// Calculate discount and final amount
$discount = $eligible
    ? ($orderAmount * $discountRate / 100)
    : 0;

$finalAmount = $orderAmount - $discount;

// Display bill
echo "<h2>Discount Bill</h2>";
echo "Order Amount: ₹" . $orderAmount . "<br>";
echo "Discount: ₹" . $discount . "<br>";
echo "Final Amount: ₹" . $finalAmount;
?>

Expected Output

Discount Bill

Order Amount: ₹2000
Discount: ₹200
Final Amount: ₹1800

How Does This Work?

  1. The program stores the order amount.

  2. The comparison operator checks whether the order reaches ₹1,500.

  3. The ternary operator calculates the discount only when eligible.

  4. The arithmetic operators calculate the final amount.

  5. The output statements display the bill.

Real-world application: This logic can be extended to an e-commerce application with coupon codes, membership discounts, delivery charges, taxes, and database-backed orders.

For production applications, validate all prices and discount rules on the server rather than trusting values submitted by a browser.

12. Common Mistakes Beginners Should Avoid

When learning PHP operators, beginners often make the following mistakes.

Mistake 1: Confusing = With ==

$age = 18;

The = operator assigns a value.

$age == 18;

The == operator compares values.

Mistake 2: Ignoring Data Types

var_dump(5 == "5");
var_dump(5 === "5");

The first expression evaluates to true under PHP's normal comparison rules, while the second evaluates to false because the types differ.

Mistake 3: Incorrect Logical Conditions

if ($age >= 18 && $hasLicense) {
    echo "Eligible";
}

The AND operator requires both conditions to be true.

Mistake 4: Forgetting Operator Precedence

$result = 10 + 5 * 2;

This produces 20, not 30, because multiplication takes precedence over addition.

Mistake 5: Dividing by Zero

$result = $a / $b;

Before dividing, make sure $b is not zero.

Mistake 6: Using Ternary Operators for Complex Logic

Long, nested ternary expressions can make code difficult to understand. Use if-else statements when the logic involves several conditions or actions.

13. Practice Exercises for Beginners

Try the following exercises to strengthen your understanding of PHP operators.

Exercise 1: Arithmetic Operators

Create two variables and display their sum, difference, product, quotient, and remainder.

Exercise 2: Assignment Operators

Start with $total = 100, add 50, subtract 20, and display the final value.

Exercise 3: Comparison Operators

Create a variable for age and check whether the person is 18 or older.

Exercise 4: Logical Operators

Check whether a customer is eligible for free delivery based on order amount and membership status.

Exercise 5: Increment and Decrement

Create a variable with the value 10. Increase it by one and then decrease it by one.

Exercise 6: Ternary Operator

Use the ternary operator to check whether a number is even or odd.

Exercise 7: Student Result

Create three subject marks and check whether all subjects meet the passing requirement.

Exercise 8: Discount Calculator

Calculate a 15% discount on a product priced at ₹2,500.

Exercise 9: Product Availability

Check whether a product is in stock and display an appropriate message.

Exercise 10: Shopping Bill

Calculate the subtotal of three products, apply a discount, add a delivery charge, and display the final amount.

14. Frequently Asked Questions About PHP Operators

What are operators in PHP?

Operators are symbols or keywords used to perform calculations, assign values, compare data, combine conditions, and manipulate values in PHP programs.

What are the main types of PHP operators?

The main categories include arithmetic, assignment, comparison, logical, increment and decrement, string, and conditional operators. PHP also supports bitwise, array, type, error-control, and other specialized operators.

What is the difference between = and == in PHP?

The = operator assigns a value to a variable, whereas == compares two values for equality after applicable type conversions.

What is the difference between == and ===?

The == operator compares values using PHP's comparison rules. The === operator checks whether the values are equal and have the same type.

What is the use of the % operator in PHP?

The modulus operator % returns the remainder after division. It is often used for checking whether a number is even or odd.

What is the ternary operator in PHP?

The ternary operator is a short conditional expression that chooses one of two values depending on whether a condition is true or false.

What are logical operators used for?

Logical operators combine or reverse conditions. They are commonly used in authentication, eligibility checks, form validation, and business rules.

Where are PHP operators used in real-world projects?

PHP operators are used in shopping carts, billing applications, student result systems, salary calculations, inventory management, access control, and dynamic website development.

Conclusion

In this Core PHP Module 3 tutorial, we learned about arithmetic, assignment, comparison, logical, increment, decrement, ternary, and string operators, along with operator precedence.

We also developed practical examples for shopping bills, student results, product availability, and discount calculations.

PHP operators are fundamental to programming because they allow applications to calculate values, compare information, and make decisions.

Practice each example yourself, change the values, and observe how the output changes. Once you understand these operators, you will be ready to learn conditional statements and loops in the next module.