HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations, such as addition, subtraction, multiplication, and more. They are the same symbols you use on a standard calculator.


Table of Arithmetic Operators

The following table lists the arithmetic operators supported by PHP:

Operator Name Description Example ($x=10, $y=4)
+ Addition Sum of $x and $y $x + $y (14)
- Subtraction Difference of $x and $y $x - $y (6)
* Multiplication Product of $x and $y $x * $y (40)
/ Division Quotient of $x and $y $x / $y (2.5)
% Modulus Remainder of $x divided by $y $x % $y (2)
** Exponentiation Result of raising $x to the $y'th power $x ** $y (10,000)

Understanding Modulus (%)

The **Modulus** operator is often confusing for beginners. It does not return the result of division; instead, it returns what is left over (the remainder).

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

    echo $x % $y; // Outputs: 1 (because 3 goes into 10 three times, leaving 1 left over)
?>

Exponentiation (**)

Introduced in PHP 5.6, this operator provides a simple way to calculate powers (e.g., $x squared or cubed).

<?php
    $x = 5;
    $y = 2;

    echo $x ** $y; // Outputs: 25 (5 to the power of 2)
?>
Automatic Conversion: If you divide two integers and the result is a decimal, PHP will automatically return a **Float** type.
Common Use Case: The Modulus operator (%) is frequently used to determine if a number is Even or Odd (e.g., $num % 2 == 0 is even).

Key Points to Remember

  • Use standard symbols (+, -, *, /) for basic math.
  • Modulus (%) returns only the remainder.
  • Exponentiation (**) is for calculating powers.
  • Division between integers can result in a float.
  • Use parentheses to control the **Order of Operations** (PEMDAS).