Skip to main content
PHP for Beginners
CHAPTER 05 Beginner

PHP Operators

Updated: May 12, 2026
15 min read

# Chapter 5: PHP Operators

1. Introduction

Welcome to Chapter 5! Now that we have variables holding our data, we need ways to manipulate that data. This is where operators come in. Operators are special symbols that perform operations on variables and values. Whether you want to add two numbers, compare if passwords match, or combine two strings, operators are the tools you need. In this chapter, we will cover Arithmetic, Assignment, Comparison, Logical, and String operators.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Perform mathematical calculations using Arithmetic Operators.
  • Update variable values efficiently using Assignment Operators.
  • Compare values using Comparison Operators.
  • Chain conditions together using Logical Operators.
  • Combine text using String Operators.

3. Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations, such as addition, subtraction, multiplication, and division.
  • + (Addition): $x + $y
  • - (Subtraction): $x - $y
  • * (Multiplication): $x * $y
  • / (Division): $x / $y
  • % (Modulus/Remainder): $x % $y
  • (Exponentiation): $x $y (x to the power of y)
php
12345678
<?php
$x = 10;
$y = 3;

echo $x + $y; // Outputs: 13
echo "<br>";
echo $x % $y; // Outputs: 1 (10 divided by 3 is 9, remainder 1)
?>

4. Assignment Operators

Assignment operators are used to write a value to a variable. The most basic one is =. However, PHP has shorthand assignment operators to update existing variables.
  • = (Assign): $x = 5
  • += (Add and assign): $x += 5 (Same as $x = $x + 5)
  • -= (Subtract and assign): $x -= 5
  • *= (Multiply and assign): $x *= 5
php
12345
<?php
$score = 50;
$score += 10; // Adds 10 to the current score
echo $score;  // Outputs: 60
?>

5. Comparison Operators

Comparison operators compare two values and return a Boolean (true or false). These are vital for conditional statements.
  • == (Equal): Returns true if values are equal.
  • === (Identical): Returns true if values are equal AND of the same data type.
  • != (Not equal): Returns true if values are not equal.
  • > (Greater than): Returns true if left is strictly greater than right.
  • < (Less than): Returns true if left is strictly less than right.
  • >= (Greater than or equal to)
  • <= (Less than or equal to)
php
1234567
<?php
$a = 5;      // Integer
$b = "5";    // String

var_dump($a == $b);  // Outputs: bool(true) - because values are 5
var_dump($a === $b); // Outputs: bool(false) - because types are different (int vs string)
?>

6. Logical Operators

Logical operators are used to combine multiple conditional statements.
  • && or and (And): True if BOTH conditions are true.
  • || or or (Or): True if AT LEAST ONE condition is true.
  • ! (Not): Reverses the boolean value. True becomes false, false becomes true.
php
1234567
<?php
$age = 20;
$has_ticket = true;

// Both must be true
var_dump($age >= 18 && $has_ticket == true); // Outputs: bool(true)
?>

7. String Operators

There are two specific operators for strings. They are used to concatenate (join together) strings.
  • . (Concatenation): Joins two strings together.
  • .= (Concatenation assignment): Appends a string to an existing string variable.
php
1234567891011
<?php
$first_name = "John";
$last_name = "Doe";

$full_name = $first_name . " " . $last_name;
echo $full_name; // Outputs: John Doe

$greeting = "Hello";
$greeting .= " World!"; // Appends to the greeting
echo $greeting; // Outputs: Hello World!
?>

8. Real-World Examples

Imagine an e-commerce cart. You need to calculate the total price, apply a discount, and check if the user qualifies for free shipping.
php
123456789101112131415161718
<?php
$item_price = 25.50;
$quantity = 3;
$shipping_cost = 5.00;

// Arithmetic
$subtotal = $item_price * $quantity;

// Assignment
$total = $subtotal;
$total += $shipping_cost; 

// Comparison
$qualifies_for_free_shipping = ($subtotal >= 50); // Returns true

// String Concatenation
echo "Your total is $" . $total;
?>

9. Output Explanations

In the cart example, $itemprice * $quantity results in 76.5. $total += $shippingcost adds 5, making $total 81.5. Because 76.5 is greater than 50, $qualifiesforfreeshipping becomes true. The final echo concatenates the text and the number, resulting in: Your total is $81.5.

10. Common Mistakes

  • Confusing = and ==: Using $x = 5 inside a comparison instead of $x == 5. A single = *assigns* the value, it does not compare it!
  • Ignoring Data Types in Comparisons: Using == when verifying critical data (like passwords or strict ID checks). Always prefer === to avoid unexpected type juggling bugs.
  • Forgetting spaces in string concatenation: $first.$last might output JohnDoe without a space. You must explicitly add " ".

11. Best Practices

  • Always use the identical operator === instead of == to prevent hidden bugs caused by PHP automatically changing data types during comparison.
  • Use parentheses () to group complex logical operations to make the evaluation order clear. Example: if ( ($a && $b) || $c ).

12. Exercises

  1. 1. Use arithmetic operators to calculate the area of a rectangle (length * width) and echo the result.
  1. 2. Create a variable and use the .= operator to build a paragraph of text from three separate sentences.
  1. 3. Compare the integer 10 and the string "10" using both == and === and vardump() the results.

13. Mini Project: Simple Calculator Backend

Task: Build a script that mimics a calculator. Define two number variables and output their addition, subtraction, multiplication, and division in a neatly formatted HTML list.
php
1234567891011121314151617181920
<?php
// Calculator Inputs
$num1 = 24;
$num2 = 4;
?>

<!DOCTYPE html>
<html>
<head><title>PHP Calculator</title></head>
<body>
    <h2>Calculator Results for <?php echo $num1; ?> and <?php echo $num2; ?></h2>
    <ul>
        <li><strong>Addition:</strong> <?php echo $num1 + $num2; ?></li>
        <li><strong>Subtraction:</strong> <?php echo $num1 - $num2; ?></li>
        <li><strong>Multiplication:</strong> <?php echo $num1 * $num2; ?></li>
        <li><strong>Division:</strong> <?php echo $num1 / $num2; ?></li>
        <li><strong>Modulus:</strong> <?php echo $num1 % $num2; ?></li>
    </ul>
</body>
</html>

14. Coding Challenges

Challenge 1: You are building an ATM script. Define a variable $balance as 100 and $withdrawamount as 40. Write a logical comparison that returns true ONLY IF the $withdrawamount is less than or equal to the balance AND the $withdraw_amount is greater than 0.
php
1234567
<?php
// Solution Snippet
$balance = 100;
$withdraw_amount = 40;
$is_valid_transaction = ($withdraw_amount <= $balance && $withdraw_amount > 0);
var_dump($is_valid_transaction);
?>

15. MCQs with Answers

1. What does the % operator do? A) Calculates percentages B) Divides two numbers C) Returns the remainder of a division D) Multiplies two strings *Answer: C*

2. Which operator checks if two values are equal AND of the exact same data type? A) = B) == C) === D) !== *Answer: C*

3. What will be the value of $x after this code runs? $x = 10; $x += 5; A) 5 B) 10 C) 15 D) Error *Answer: C*

16. Interview Questions

Q: Explain the difference between == and ===. *A:* The == operator is the equality operator. It checks if the values are the same, performing type coercion if necessary (e.g., 5 == "5" is true). The === operator is the identical operator. It checks if both the values AND the data types are exactly the same without any coercion (e.g., 5 === "5" is false).

Q: What is the concatenation operator in PHP? *A:* In PHP, the dot . is used to concatenate (join) strings. This is different from many other languages (like JavaScript or Python) which use the + sign for string concatenation.

17. FAQs

Q: Can I use + to join strings in PHP? *A:* No. If you try to use + to join strings in PHP, it will attempt to convert those strings into numbers and perform mathematical addition, leading to errors or unexpected results. Always use the . dot operator for strings.

18. Summary

Operators are the action verbs of PHP! You learned how to do math with Arithmetic operators, update variables quickly with Assignment operators, evaluate logic using Comparison and Logical operators, and build dynamic text using String concatenation.

19. Next Chapter Recommendation

We have been hardcoding all our variables so far. In Chapter 6: PHP Input and Output, we will learn how to make our applications interactive by capturing input directly from the user using basic HTML forms!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·