PHP Integers

An integeropen in new window 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 operatorsopen in new window. The basic operators are as follows:

operatoroperation
+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 Functionsopen in new window which can be used to complete common calculations.

abs() Function

The abs()open in new window 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()open in new window 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()open in new window function will return the square root of the provided number.

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

fmod() Function

The fmod()open in new window 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()open in new window 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 operatoropen in new window 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.

operatoroperation
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = 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 operatorsopen in new window are used to increase or decrease a variable by 1.

<?php 
  $var2 = 4;

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

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