PHP Numbers

In PHP, numbers can be represented using different types of numerical data types. Here's a summary of how numbers work in PHP:


PHP Number Types

  1. Integer
    Whole numbers without a decimal point.
    Range: Typically from -2,147,483,648 to 2,147,483,647 (platform-dependent).

    $x = 42; var_dump($x); // int(42)
  2. Float (Double)
    Numbers with a decimal point or in exponential form.
    Useful for calculations involving fractions.

    $y = 3.14; var_dump($y); // float(3.14)
  3. Numeric Strings
    Strings that contain valid numbers can be used in arithmetic operations.

    $num = "100"; $sum = $num + 50; // PHP will convert the string to an integer var_dump($sum); // int(150)

PHP Functions for Numbers

  • is_int($var) or is_integer($var) — Checks if a variable is an integer.

  • is_float($var) or is_double($var) — Checks if a variable is a float.

  • is_numeric($var) — Checks if a variable is a number or a numeric string.

var_dump(is_int(123)); // true var_dump(is_float(3.14)); // true var_dump(is_numeric("100")); // true

Math Operations

PHP supports standard arithmetic operators:

$x = 10; $y = 3; echo $x + $y; // Addition echo $x - $y; // Subtraction echo $x * $y; // Multiplication echo $x / $y; // Division echo $x % $y; // Modulus

Common Math Functions

  • abs($x) – Absolute value

  • pow($x, $y) – Exponentiation

  • sqrt($x) – Square root

  • round($x) – Round to nearest integer

  • floor($x) – Round down

  • ceil($x) – Round up

  • rand(min, max) – Random number