PHP Math


PHP ordinary mathematical calculations directly using the arithmetic operator:

  1. +: Addition
  2. -: Subtraction
  3. *: Multiplication
  4. /: Division
  5. %: modulo, get the remainder of A divided by B
  6. ++: Increment, this value is incremented by 1
  7. -: decrement, decrement by 1

addition, subtraction, multiplication and division calculation

$x = 10;
$y = 2;
$result = $x + $y; // Result: 12
$result = $x - $y; // Result: 8
$result = $x * $y; // Result: 20
$result = $x /$y; // Result: 5

One subtraction operator(-) can also be used alone, called inversion, that is, to obtain a negative number:

$x = 10;
$result = - $x; // Result: -10

Tip

The division operator(/) always returns a floating-point number, even if the two operands are integers(or integers converted from strings).


PHP modulo

The modulus is the remainder divided by two numbers:

$x = 10;
$y = 3;
$resule = $x% $y; // Results: 1

Tip

($x% $y) The result of modulo is also negative when $x is negative.

Modulus calculation is often used in various loop judgments, such as taking out even-numbered records.


PHP Increment

Increment means to increase a value by 1 and return the value, which is divided into:

  1. ++ $x: pre-increment, the value of $x is incremented by 1 and returns $x
  2. $x ++: post-increment, returns the value of $x and adds $x

The following example shows the difference:

$x = $y = 10;
echo ++ $x. '<br />';
echo $x. '<br />';
echo $y ++. '<br />';
echo $y;

The output is as follows:

11
11
10
11

PHP decrement

Decrement, in contrast to incrementing, means decreasing a value by 1 and returning it to:

  1. - $x: pre-decrement, the value of $x minus 1 and return $x
  2. $x--: After descending, returns $x and decrements $x by 1

The difference between pre-decrement and post-decrement can be referred to the difference between pre-increment and post-increment.

Tip

A NULL value is returned with NULL instead of -1, but the result of incrementing NULL is 1.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook