PHP ยท Chapter 9 of 44

PHP Numbers

PHP supports integers (whole numbers) and floats (decimal numbers). PHP automatically detects the numeric type based on the value assigned, and it can handle very large numbers using scientific notation.

PHP provides functions like is_int(), is_float() and is_numeric() to check the type or format of a value, which is useful when validating user input from forms.

Syntax
is_int($x);
is_float($x);
is_numeric($x);

Integers and floats

Integers must have no decimal point and can be positive or negative. Floats (also called doubles) can include a decimal point or be written in exponential form like 3.0e3.

Checking numeric values

is_numeric() checks whether a value is a number or a numeric string, which is handy when validating data submitted through an HTML form.

Example 1 (php)
<?php
  $x = 10;
  $y = 10.5;
  var_dump(is_int($x));
  var_dump(is_float($y));
?>
Output
bool(true)
bool(true)

is_int() and is_float() confirm the numeric subtype of each variable.

Example 2 (php)
<?php
  $input = "123";
  var_dump(is_numeric($input));
?>
Output
bool(true)

is_numeric() returns true for numeric strings as well as actual numbers.

Key points

  • PHP has integer and float numeric types.
  • is_int(), is_float() and is_numeric() check numeric types.
  • Numeric strings like "123" are treated as numeric by is_numeric().
  • PHP can represent very large or very small numbers using scientific notation.
๐Ÿ’ก Note: Be careful comparing floats for exact equality, since floating point arithmetic can introduce tiny rounding errors.

๐Ÿ“ Quick Quiz

1. Which function checks if a value is numeric (including numeric strings)?

2. Which type has no decimal point?

3. What can cause tiny errors when comparing numbers?