PHP Numbers
In PHP, there are two main types of numbers: integers and floating-point numbers.
An integer is a whole number, either positive or negative. It can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation. For example, the following are all valid integers in PHP:
- 10 (decimal)
- 0xA (hexadecimal)
- 012 (octal)
- 0b1010 (binary)
Floating-point numbers, also known as floats, are numbers with a decimal point. They can also be positive or negative. For example, the following are all valid floating-point numbers in PHP:
- 3.14
- -0.01
- 6.022e23 (scientific notation)
PHP also has a special type called a "double", which is a more precise version of a float. It is generally recommended to use floats instead of doubles, unless you need the extra precision.
You can use the following functions to check the type of a number in PHP:
- is_int() for integers
- is_float() for floating-point numbers
- is_numeric() for both integers and floating-point numbers
For example:
$num1 = 10; $num2 = 3.14; if (is_int($num1)) { echo "$num1 is an integer\n"; } if (is_float($num2)) { echo "$num2 is a float\n"; } if (is_numeric($num1)) { echo "$num1 is a number\n"; } if (is_numeric($num2)) { echo "$num2 is a number\n"; }
Output:
10 is an integer 3.14 is a float 10 is a number 3.14 is a number