What are Operators?

In the last lesson, you learned that variables are like containers for data. Operators are the special symbols that act as tools to perform operations on these variables. You use them for everything from basic math to making complex decisions in your code.

We can group them into a few main categories.


1. Arithmetic Operators

These are the operators you use for doing mathematical calculations, just like on a calculator.

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division
  • % : Modulus (gives you the remainder of a division)
<?php
    $x = 10;
    $y = 3;

    echo $x + $y; // Outputs 13
    echo "<br>";
    echo $x * $y; // Outputs 30
    echo "<br>";
    echo $x % $y; // Outputs 1 (because 10 divided by 3 is 3 with a remainder of 1)
?>

2. Assignment Operators

The most basic assignment operator is the equals sign =. It assigns the value on the right to the variable on the left. There are also handy shorthand operators.

<?php
    $a = 20;

    // This is the long way
    $a = $a + 5; // $a is now 25
    
    // This is the short way (and preferred)
    $a += 5;     // $a is now 30 (25 + 5)
?>

3. Comparison Operators

These operators are used to compare two values and they are essential for making decisions in your code. The result of a comparison is always a boolean value: true or false.

  • == : **Equal**. Returns true if the values are the same.
  • === : **Identical**. Returns true if the values AND the data types are the same. (Very important!)
  • != : **Not Equal**.
  • !== : **Not Identical**.
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to
<?php
    $num = 5;
    $text = "5";
    
    var_dump($num == $text);  // Outputs: bool(true) because the values are the same
    echo "<br>";
    var_dump($num === $text); // Outputs: bool(false) because the types (Integer vs. String) are different
?>

Pro Tip: Always try to use the identical operator (===) when possible for stricter and safer comparisons.


4. Logical Operators

These operators are used to combine multiple conditions together.

  • && (And): Returns true only if both conditions are true.
  • || (Or): Returns true if at least one of the conditions is true.
  • ! (Not): Reverses the result. !true becomes false.
<?php
    $age = 25;
    $has_license = true;

    // Is the person over 18 AND has a license?
    var_dump($age > 18 && $has_license == true); // Outputs: bool(true)
?>

Understanding operators is crucial because they are the foundation for the next topic: control structures, where we'll make our code start making decisions!