PHP Integers

An integer is any whole number, either positive or negative. To set a variable to a number, provide the number literal with no quotes.

<?php
  // setting variables to numbers
  $var1 = 3;
  $var2 = 4;
?>

Arithmetic Operators

PHP can handle basic mathematical calculation by using arithmetic operators. The basic operators are as follows:

operator operation
+ addition
- subtraction
* multiplication
/ division

NOTE

PHP follows the (PEMDAS) orders of operation.

Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction

<?php
  // setting variables to numbers
  $var1 = 3;
  $var2 = 4;

  // basic math calculation
  echo ((1 + 2 + $var1) * $var2) / 2 - 5; // 7
?>

Mathematical Functions

PHP has many predefined Math Functions which can be used to complete common calculations.

abs() Function

The abs() function will return the absolute value of the provided number.

<?php
  // getting absolute value of an expression
  echo abs(0 - 300); // 300
?>

pow() Function

The pow() function will return the base number raised the power of the exp number.

<?php
  // getting value of 2 to power of 8
  echo pow(2, 8); // 256
?>

sqrt() Function

The sqrt() function will return the square root of the provided number.

<?php
  // getting square root of 100
  echo sqrt(100); // 10
?>

fmod() Function

The fmod() function will returns the floating point remainder of diving the dividend (first argument) by the divisor (second argument).

<?php
  // getting remainder of 20 divided by 7
  echo fmod(20, 7); // 6
?>

rand() Function

The rand() function will return a random integer. A min and max parameters can be provided to give a range for the random integer. If no parameters are provided the random integer will be between 0 and the largest possible random number.

<?php
  // getting a random integer
  echo rand();

  // getting a random integer between 1 and 10
  echo rand(1, 10);
?>

Assignment Operators

The basic assignment operator is the equal sign (=), but PHP has other assignment operators, sometimes called "combined operators". These "combined operators" can be used as a shorthand for mathematical expressions.

operator operation
x += y x = x + y
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y
<?php 
  $var2 = 4;

  // addition
  $var2 += 4; echo $var2; // 8

  // subtraction
  $var2 -= 4; echo $var2; // 4

  // multiplication
  $var2 *= 3; echo $var2; // 12

  // division
  $var2 /= 4; echo $var2; // 3
?>

Incrementing/Decrementing Operators

The incrementing/decrementing operators are used to increase or decrease a variable by 1.

<?php 
  $var2 = 4;

  // Increment
  $var2++; echo $var2; // 5

  // Decrement
  $var2--; echo $var2; // 4
?>