PHP Operators Tutorial 🎯

beginner
5 min

PHP Operators Tutorial 🎯

Welcome to our PHP Operators Tutorial! In this comprehensive guide, we'll explore various types of PHP operators, their usage, and real-world examples. Let's dive in!

Understanding Operators πŸ“

Operators in PHP are symbols that perform specific mathematical, comparison, or logical operations on variables or values. They help in writing more complex and meaningful code.

Basic Arithmetic Operators πŸ’‘

Arithmetic operators are used for mathematical operations. Here are the most common ones:

  1. Addition (+)
  2. Subtraction (-)
  3. Multiplication (*)
  4. Division (/)
  5. Modulus (%)
  6. Increment (++)
  7. Decrement (--)

Example πŸ“:

php
<?php $a = 5; $b = 3; $sum = $a + $b; // 8 $difference = $a - $b; // 2 $product = $a * $b; // 15 $quotient = $a / $b; // 1.666666666667 (float) $remainder = $a % $b; // 1 (remainder when 5 is divided by 3) $a++; // Increment $a by 1 (now $a is 6) $b--; // Decrement $b by 1 (now $b is 2) ?>

Comparison Operators πŸ’‘

Comparison operators are used to compare two values and return a boolean result (true or false). Here are the comparison operators:

  1. Equal to (==)
  2. Not equal to (!=)
  3. Greater than (>)
  4. Less than (<)
  5. Greater than or equal to (>=)
  6. Less than or equal to (<=)

Example πŸ“:

php
<?php $a = 5; $b = 3; $equal = ($a == $b); // false $notEqual = ($a != $b); // true $greater = ($a > $b); // true $less = ($a < $b); // false $greaterOrEqual = ($a >= $b); // false $lessOrEqual = ($a <= $b); // true ?>

Logical Operators πŸ’‘

Logical operators are used to combine conditional statements. Here are the logical operators:

  1. AND (&&)
  2. OR (||)
  3. XOR (^)
  4. NOT (!)

Example πŸ“:

php
<?php $a = 5; $b = 3; $and = ($a > 3) && ($b < 5); // true (since 5 > 3 and 3 < 5) $or = ($a > 3) || ($b < 5); // true (since either 5 > 3 or 3 < 5) $xor = ($a > 3) ^ ($b < 5); // false (both conditions are true, so XOR returns false) $not = !($a > 3); // false (since $a > 3 is true, NOT reverses the boolean value) ?>
Quick Quiz
Question 1 of 1

Which operator is used to compare whether two values are equal in PHP?


We've covered the basics of PHP operators. In the next lesson, we'll dive deeper into more complex operators and explore some practical examples in real-world scenarios. Stay tuned! 🎯