HOME HTML EDITOR C JAVA PHP

PHP Operators

Operators are used to perform operations on variables and values. PHP divides operators into several groups based on their functionality.

1. Arithmetic Operators

These are used with numeric values to perform common mathematical operations like addition, subtraction, and multiplication.

<?php
  $x = 10;
  $y = 4;

  echo $x + $y; // Addition (14)
  echo $x - $y; // Subtraction (6)
  echo $x * $y; // Multiplication (40)
  echo $x / $y; // Division (2.5)
  echo $x % $y; // Modulus - Remainder (2)
  echo $x ** $y; // Exponentiation (10000)
?>

2. Assignment Operators

The basic assignment operator is =. It means that the left operand gets set to the value of the expression on the right.

<?php
  $x = 10;
  $x += 5; // Same as $x = $x + 5
  echo $x; // Outputs: 15
?>

3. Comparison Operators

Comparison operators are used to compare two values (number or string) and return a Boolean (true/false).

<?php
  $x = 100;
  $y = "100";

  var_dump($x == $y); // Returns true because values are equal
  var_dump($x === $y); // Returns false because types are not identical
  var_dump($x != $y); // Not equal (false)
  var_dump($x > $y); // Greater than (false)
?>

4. Logical Operators

Logical operators are used to combine conditional statements.

5. Increment / Decrement Operators

These are used to increment (increase) or decrement (decrease) a variable's value.

<?php
  $x = 10;
  echo ++$x; // Pre-increment (11)
  echo $x--; // Post-decrement (Outputs 11, then becomes 10)
?>
Important: Always remember the difference between == (Equal) and === (Identical). Identical checks both the value and the data type.