HOME HTML EDITOR C JAVA PHP

PHP Numbers

In PHP, there are three main numeric types: Integers, Floats, and Number Strings. PHP automatically handles type conversion, but it is important to know how to check and manipulate them.

1. PHP Integers

An integer is a number without decimals. It must have at least one digit and cannot contain commas or blanks. You can use is_int() to check if a variable is an integer.

<?php
  $x = 5985;
  var_dump(is_int($x)); // Returns: true

  $y = 59.85;
  var_dump(is_int($y)); // Returns: false
?>

2. PHP Floats

A float is a number with a decimal point or a number in exponential form. You can use is_float() to check the type.

<?php
  $x = 10.365;
  var_dump(is_float($x)); // Returns: true
?>

3. PHP Infinity

A numeric value that is larger than PHP_FLOAT_MAX is considered infinite. PHP has functions like is_finite() and is_infinite() to check this.

<?php
  $x = 1.9e411;
  var_dump($x); // Returns: float(INF)
?>

4. PHP NaN (Not a Number)

NaN is used for impossible mathematical operations. You can check it using is_nan().

<?php
  $x = acos(8);
  var_dump($x); // Returns: float(NaN)
?>

5. PHP Numerical Strings

The is_numeric() function is used to find out whether a variable is a number or a numeric string.

<?php
  $x = 5985; // Integer
  $y = "5985"; // Numeric String
  $z = "Hello"; // String

  var_dump(is_numeric($x)); // true
  var_dump(is_numeric($y)); // true
  var_dump(is_numeric($z)); // false
?>
Helpful Tip: is_numeric() is very useful when validating form data, as user input from a text field is always a string, even if it contains a number.