Web Development /PHP Programming / Lesson
Web Development

Operators

Learn how PHP operators are used to perform calculations, assign values, compare data, combine logical conditions, manipulate strings and arrays, handle null values, and build concise expressions in modern PHP applications.

🎯

Learning Objectives

["Explain what operators are and how operands are used in PHP expressions.","Use arithmetic operators to perform mathematical calculations.","Use assignment and compound assignment operators to update variables.","Distinguish between loose comparison and strict comparison in PHP.","Use logical operators to combine and negate Boolean conditions.","Use increment, decrement, string, and array operators correctly.","Apply the null coalescing and null coalescing assignment operators.","Use the ternary operator appropriately for concise conditional expressions.","Understand operator precedence and use parentheses to make expressions clear.","Recognize advanced operators such as bitwise operators and instanceof."]

📖

Lesson Content

Introduction to PHP Operators

Operators are symbols or keywords that tell PHP to perform an operation on one or more values. The values being operated on are called operands.

For example:

$total = 10 + 5;

In this expression, + is the operator, while 10 and 5 are operands. PHP evaluates the expression and stores the result in $total.

Operators are fundamental to PHP programming because they allow applications to calculate values, compare information, make decisions, update variables, process strings, manipulate arrays, and handle optional data.


1. Arithmetic Operators

Arithmetic operators are used for mathematical calculations.

OperatorNameExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52
%Modulus10 % 31
**Exponentiation2 ** 38

Addition

$price = 100;
$delivery = 20;

$total = $price + $delivery;

echo $total;

The result is 120.

Subtraction

$balance = 500;
$withdrawal = 150;

$remaining = $balance - $withdrawal;

echo $remaining;

The result is 350.

Multiplication

$quantity = 4;
$price = 250;

$total = $quantity * $price;

echo $total;

The result is 1000.

Division

$total = 1000;
$people = 4;

$share = $total / $people;

echo $share;

The result is 250.

Modulus

The modulus operator returns the remainder after division.

$remainder = 17 % 5;

echo $remainder;

The result is 2.

Modulus is useful for checking whether a number is even or odd:

$number = 20;

if ($number % 2 === 0) {
    echo 'Even number';
} else {
    echo 'Odd number';
}

Exponentiation

$result = 2 ** 4;

echo $result;

The result is 16.


2. Assignment Operators

The assignment operator stores a value in a variable.

$name = 'Ade';

PHP also provides compound assignment operators that combine an operation with assignment.

OperatorExampleEquivalent Idea
=$x = 10Assign 10 to x
+=$x += 5$x = $x + 5
-=$x -= 5$x = $x - 5
*=$x *= 5$x = $x * 5
/=$x /= 5$x = $x / 5
%=$x %= 5$x = $x % 5
**=$x **= 2$x = $x ** 2

Example:

$score = 50;

$score += 10;
$score -= 5;
$score *= 2;

echo $score;

Compound assignment operators make repeated variable updates shorter and easier to read.


3. Comparison Operators

Comparison operators compare values and normally produce a Boolean result: true or false.

OperatorMeaning
==Equal in value after PHP’s comparison rules
===Identical in value and type
!=Not equal
<>Not equal
!==Not identical in value or type
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
<=>Spaceship comparison

Loose Comparison

$value = 10;

var_dump($value == '10');

The == operator performs a non-strict comparison according to PHP’s comparison rules.

Strict Comparison

$value = 10;

var_dump($value === '10');

The === operator checks both value and type. The integer 10 and string '10' are therefore not identical.

Strict comparisons are generally useful when an application needs to distinguish between different data types.

Relational Comparisons

$age = 20;

if ($age >= 18) {
    echo 'Adult';
}

The Spaceship Operator

The spaceship operator <=> returns:

  • -1 when the left value is less than the right value.
  • 0 when the values compare equally.
  • 1 when the left value is greater than the right value.
echo 10 <=> 20;
echo 20 <=> 20;
echo 30 <=> 20;

This operator is especially useful when creating custom sorting logic.


4. Logical Operators

Logical operators combine or modify Boolean expressions.

OperatorName
&&Logical AND
||Logical OR
!Logical NOT
andLogical AND
orLogical OR
xorLogical exclusive OR

Logical AND

With &&, both conditions must be true.

$age = 25;
$has_ticket = true;

if ($age >= 18 && $has_ticket) {
    echo 'Access granted';
}

Logical OR

With ||, at least one condition must be true.

$is_admin = false;
$is_manager = true;

if ($is_admin || $is_manager) {
    echo 'Access granted';
}

Logical NOT

The ! operator reverses a Boolean value.

$logged_in = false;

if (!$logged_in) {
    echo 'Please log in';
}

and, or and xor

PHP also provides the keyword forms and, or, and xor.

$a = true;
$b = false;

var_dump($a and $b);
var_dump($a or $b);
var_dump($a xor $b);

Be careful when using and and or in assignment expressions because their precedence differs from && and ||. Parentheses can make the intended logic explicit.

$result = ($a && $b);

5. Increment and Decrement Operators

The increment operator ++ increases a value by one, while the decrement operator -- decreases a value by one.

$counter = 5;

$counter++;

echo $counter;

The result is 6.

$counter = 5;

$counter--;

echo $counter;

The result is 4.

Prefix and Postfix Forms

$number = 5;

echo ++$number;

With prefix increment, the value is incremented before the expression uses it.

$number = 5;

echo $number++;

With postfix increment, the current value is used first and then incremented.

The same concept applies to --.


6. String Operators

PHP uses the dot operator . to concatenate strings.

$first_name = 'Ade';
$last_name = 'Johnson';

$full_name = $first_name . ' ' . $last_name;

echo $full_name;

The compound concatenation operator .= appends text to an existing string.

$message = 'Welcome';

$message .= ' to Dwallnet Technologies.';

echo $message;

String concatenation is frequently used when building messages, HTML output, URLs, filenames, and other text values.


7. Array Operators

PHP provides operators specifically for combining and comparing arrays.

OperatorMeaning
+Union
==Equal arrays
===Identical arrays
!=Not equal
<>Not equal
!==Not identical

Array Union

$first = array(
    'name' => 'Ade',
    'course' => 'PHP'
);

$second = array(
    'course' => 'JavaScript',
    'level' => 'Beginner'
);

$result = $first + $second;

print_r($result);

For array union, keys from the left-hand array are preserved when the same keys exist in both arrays.

Array Equality

$a = array(
    'name' => 'Ade',
    'age' => 25
);

$b = array(
    'age' => 25,
    'name' => 'Ade'
);

var_dump($a == $b);

The == operator compares arrays based on their key/value pairs without requiring the same order.

The === operator is stricter and requires the same key/value pairs in the same order and with matching types.


8. Null Coalescing Operator

The null coalescing operator ?? provides a convenient way to use a fallback value when a variable or array key is not set or is null.

$name = $_GET['name'] ?? 'Guest';

echo $name;

If the name parameter is available and not null, its value is used. Otherwise, Guest is used.

This is especially useful when working with form data, query parameters, configuration values, and optional array keys.

Null Coalescing Assignment

The ??= operator assigns a value only when the variable is not already set or is null.

$username = null;

$username ??= 'Guest';

echo $username;

This is a concise way to provide a default value.


9. Ternary Operator

The ternary operator provides a short way to write a simple conditional expression.

$age = 20;

$status = ($age >= 18) ? 'Adult' : 'Minor';

echo $status;

The general structure is:

condition ? value_if_true : value_if_false

Use the ternary operator when it improves readability. Avoid creating deeply nested ternary expressions because they can become difficult to understand.


10. Operator Precedence

When an expression contains several operators, PHP follows operator precedence rules to determine which operation happens first.

For example:

$result = 10 + 5 * 2;

echo $result;

Multiplication has higher precedence than addition, so the multiplication is evaluated before the addition.

Parentheses can be used to make the intended order explicit:

$result = (10 + 5) * 2;

echo $result;

Good programming practice is to use parentheses whenever an expression could be misunderstood by another developer or by your future self.

Important Assignment Precedence Example

$a = true;
$b = false;

$result = $a and $b;

Keyword and has lower precedence than assignment. Therefore, expressions involving assignment and and can produce results that may surprise beginners.

Prefer parentheses or use && when appropriate:

$result = ($a && $b);

11. Bitwise Operators

Bitwise operators work with the individual bits of integer values. They are more advanced and are commonly encountered in low-level programming, flags, permissions, binary data processing, and certain performance-sensitive applications.

OperatorPurpose
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Left shift
>>Right shift

Example:

$a = 6;
$b = 3;

echo $a & $b;

Bitwise operations should not be confused with the logical operators && and ||.


12. The instanceof Operator

The instanceof operator checks whether an object is an instance of a particular class or compatible class/interface.

class Student
{
}

$student = new Student();

var_dump($student instanceof Student);

The result is true.

This operator becomes particularly useful when working with object-oriented PHP applications.


13. Combining Operators

Real applications often use several operators in the same expression.

$price = 5000;
$quantity = 3;
$discount = 1000;

$total = ($price * $quantity) - $discount;

echo $total;

Here, multiplication is performed first because the expression is grouped using parentheses, and the discount is then subtracted.

Example: Student Result Processing

$score = 75;
$bonus = 5;

$final_score = $score + $bonus;

$status = ($final_score >= 50) ? 'Pass' : 'Fail';

echo "Final Score: " . $final_score . "<br>";
echo "Status: " . $status;

This example combines arithmetic, comparison, ternary, and string operators.


14. Operators and Input Validation

Operators are frequently used when validating user input.

$username = $_POST['username'] ?? '';
$age = (int) ($_POST['age'] ?? 0);

if ($username !== '' && $age >= 18) {
    echo 'Valid information';
} else {
    echo 'Please provide valid information';
}

Notice the use of:

  • ?? to provide safe defaults for missing input.
  • (int) to convert the age value to an integer.
  • !== to perform a strict comparison.
  • && to require both conditions to be true.
  • >= to check the minimum age.

Remember that operators do not replace proper input validation and sanitization. Data received from users should still be validated according to the application’s requirements.


15. Common Operator Mistakes

Mistake 1: Confusing Assignment and Comparison

The = operator assigns a value, while == and === compare values.

$age = 18;

if ($age === 18) {
    echo 'Correct comparison';
}

Mistake 2: Confusing == and ===

Remember that === checks both value and type.

$number = 10;

var_dump($number == '10');
var_dump($number === '10');

Mistake 3: Confusing && with &

&& is a logical AND operator, while & is a bitwise AND operator. They serve different purposes.

Mistake 4: Forgetting Parentheses

Complex expressions should be grouped clearly.

$eligible = ($age >= 18) && ($has_id === true);

Mistake 5: Overusing Ternary Expressions

The ternary operator is useful for simple conditions, but longer business logic is usually easier to maintain with ordinary if and else statements.


16. Practical Mini Project: Shopping Cart Calculation

The following example combines several PHP operators to calculate a simple shopping cart total.

<?php

$product_price = 15000;
$quantity = 3;
$discount = 5000;
$delivery_fee = 2000;

$subtotal = $product_price * $quantity;
$total = $subtotal - $discount + $delivery_fee;

$status = ($total > 0) ? 'Payment Required' : 'No Payment Required';

echo "Subtotal: ₦" . $subtotal . "<br>";
echo "Discount: ₦" . $discount . "<br>";
echo "Delivery: ₦" . $delivery_fee . "<br>";
echo "Total: ₦" . $total . "<br>";
echo "Status: " . $status;

This example demonstrates how operators can be combined to solve practical programming problems.


17. Practical Mini Project: Login Condition

<?php

$username = 'admin';
$password = 'secret123';

$input_username = 'admin';
$input_password = 'secret123';

if (
    $input_username === $username
    &&
    $input_password === $password
) {
    echo 'Login successful';
} else {
    echo 'Invalid login details';
}

This demonstrates strict comparison and logical AND in a simple authentication condition. In a real application, passwords should not be stored or compared as plain text; secure password hashing and verification should be used.


18. Best Practices When Using Operators

  • Use strict comparisons such as === when type-sensitive comparison is required.
  • Use parentheses to make complex expressions easier to understand.
  • Choose operators that clearly communicate your intention.
  • Do not confuse logical operators with bitwise operators.
  • Use ?? when providing defaults for optional values.
  • Keep ternary expressions simple and readable.
  • Be aware of operator precedence when combining multiple operators.
  • Validate external input before using it in calculations or decisions.
  • Use meaningful variable names so expressions are easier to understand.
  • Test important expressions with realistic values and edge cases.

Summary

Operators are essential building blocks of PHP programming. They allow developers to calculate values, assign and update variables, compare information, combine conditions, manipulate strings and arrays, provide fallback values, and construct concise expressions.

The major operator groups covered in this lesson include arithmetic, assignment, comparison, logical, increment/decrement, string, array, null coalescing, ternary, bitwise, and object-related operators.

A strong understanding of operators will make it easier to write conditional statements, loops, functions, form processing, database logic, authentication systems, and larger PHP applications.

💻

Code Example

<?php

$price = 15000;
$quantity = 3;
$discount = 5000;
$delivery_fee = 2000;

$subtotal = $price * $quantity;

$total = ($subtotal - $discount) + $delivery_fee;

if ($total > 0) {
    $status = 'Payment Required';
} else {
    $status = 'No Payment Required';
}

echo "Subtotal: ₦" . $subtotal . "<br>";
echo "Discount: ₦" . $discount . "<br>";
echo "Delivery: ₦" . $delivery_fee . "<br>";
echo "Total: ₦" . $total . "<br>";
echo "Status: " . $status;
⭐

Key Takeaways

["Operators perform operations on values called operands.","Arithmetic operators are used for mathematical calculations.","Assignment operators store and update values in variables.","The === operator compares both value and data type.","Logical operators are used to combine or reverse Boolean conditions.","The dot operator concatenates strings in PHP.","Array operators provide ways to combine and compare arrays.","The ?? operator provides a fallback when a value is not set or is null.","The ternary operator provides a concise expression for simple conditional logic.","Parentheses improve clarity and help control the intended order of operations."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress