·  PHP – Syntax – Operators – Arithmetic

 

- Info:

  - Arithmetic operators are used to perform mathematical operations.

  - Mathematical operations, not supported by arithmetic operators, can be performed using PHP mathematical functions.

  - This tutorial is based on http://hr.php.net/manual/en/language.operators.arithmetic.php.

 

    

Type

Name

Description

 

 

   - $b

Negation

Change sign

of $b

 

$a + $b

Addition

Sum

of $a and $b

 

$a - $b

Subtraction

Difference

of $a and $b

 

$a * $b

Multiplication

Product

of $a and $b

 

$a / $b

Division

Quotient

of $a and $b

 

$a % $b

Modulus

Remainder

of $a divided by $b

 

$a++

Post-increment

Returns

$a, then increments $a by one.

 

$a--

Post-decrement

Returns

$a, then decrements $a by one.

 

   ++$b

Pre-increment

Increments

$b by one, then returns $b.

 

   --$b

Pre-decrement

Decrements

$b by one, then returns $b.

 

- Additional Info:

  - Division ("/") returns integer if both operands are evenly divisible integers (or strings that get converted to integers).

    In all ither cases float is returned.

  - Operands of modulus ("%") are converted to integers (by stripping the decimal part) before processing.

    Result of the modulus ("%") has the same sign as the dividend (first parameter $a).

 

- Example:

  - Create PHP Console Application Test.php.

 

    Test.php

    <?php

 

      #Test variables.---------------------------------------------------------------------------

      $x          = 10;

      $y          = 20;

      

      #Arithmetic operators.---------------------------------------------------------------------

      $negate     =    -$y;    #  -20 = -20

      $add        = $x +$y;    #10+20 =  30

      $subtract   = $x -$y;    #10-20 = -10

      $multiply   = $x *$y;    #10*20 = 200

      $divide     = $x /$y;    #10/20 = 0.5    

      $modulo     = $x %$y;    #10%20 = 0*20+10 = 10

      $increment2 =     $y++;  #Store $y into increment2 and then increment $y by 1.

      $decrement2 =     $y--;  #Store $y into decrement2 and then decrement $y by 1.

      $increment1 =   ++$y;    #Increment $y by 1 and then store $y into increment1.

      $decrement1 =   --$y;    #Decrement $y by 1 and then store $y into decrement1.

     

      #Display result.---------------------------------------------------------------------------

      print($increment2);      #Replace $add with any other variable from above to see its value.

 

    ?>