PHP Numbers

PHP has three primary types of numbers: Integers, Floats, and Number Strings. Additionally, there are special types like Infinity and NaN.

Tutorials dojo strip

PHP Numbers

Main Numeric Types in PHP:

  1. Integer: Whole numbers without decimal points.
  2. Float: Numbers with decimal points or in exponential form.
  3. Number Strings: Strings that represent numeric values.

Special Numeric Types in PHP:

  • Infinity: Represents values larger than PHP_FLOAT_MAX.
  • NaN (Not a Number): Used for invalid mathematical operations.

Creating Variables

To create numeric variables, simply assign values to them:

PHP

Checking Variable Types

Use var_dump() to check the type of any variable:

PHP

PHP Integers

An integer is a whole number without any decimal part. Here are a few examples: 10, -15, 2000. Integers in PHP can be between -2147483648 and 2147483647 on 32-bit systems, and much larger on 64-bit systems.

Rules for Integers:

  • Must have at least one digit
  • No decimal point allowed
  • Can be positive or negative

Constants for Integers:

  • PHP_INT_MAX: Maximum integer
  • PHP_INT_MIN: Minimum integer
  • PHP_INT_SIZE: Size of an integer in bytes

Functions to Check Integer Type:

  • is_int()
  • is_integer() (alias of is_int())
  • is_long() (alias of is_int())

Example: Checking Integer Type

PHP

PHP Floats

A float is a number with a decimal point or in exponential form. Examples: 3.14, 0.001, 2.5E+3.

Constants for Floats:

  • PHP_FLOAT_MAX: Largest floating point number
  • PHP_FLOAT_MIN: Smallest positive floating point number
  • PHP_FLOAT_DIG: Number of decimal digits without precision loss
  • PHP_FLOAT_EPSILON: Smallest positive number x so that x + 1.0 != 1.0

Functions to Check Float Type:

  • is_float()
  • is_double() (alias of is_float())

Example: Checking Float Type

PHP

PHP Infinity

Values larger than PHP_FLOAT_MAX are considered infinite.

Functions to Check Finite/Infinite Values:

  • is_finite()
  • is_infinite()

Example: Checking Finite/Infinite Value

PHP

PHP NaN

NaN stands for “Not a Number”. It results from invalid mathematical operations.

Function to Check NaN:

  • is_nan()

Example: NaN Value

PHP

PHP Numerical Strings

To determine if a variable is numeric, use the is_numeric() function. It returns true if the variable is a number or a numeric string, and false otherwise.

Example: Checking Numeric Strings

PHP

Casting Strings and Floats to Integers

Sometimes you need to convert a value to an integer. Use (int), (integer), or intval() for this purpose.

Example: Casting to Integer

PHP

Tutorials dojo strip