PHP provides automatic data type conversion. So, if you assign an integer value to a variable, the type of that variable will automatically be an integer. Then, if you assign a string to the same variable, the type will change to a string.
This automatic conversion can sometimes break your code.
An integer is a number without any decimal part.
An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.
Here are some rules for integers:
PHP has the following predefined constants for integers:
PHP has the following functions to check if the type of a variable is integer:
A float is a number with a decimal point or a number in exponential form.
2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.
The float data type can commonly store a value up to 1.7976931348623E+308 (platform dependent), and have a maximum precision of 14 digits.
PHP has the following predefined constants for floats (from PHP 7.2):
PHP has the following functions to check if the type of a variable is float:
A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
PHP has the following functions to check if a numeric value is finite or infinite:
NaN stands for Not a Number. It is used for impossible mathematical operations.
PHP has the following functions to check if a value is not a number:
The PHP is_numeric() function can be used to find whether a variable is numeric. The function returns true if the variable is a number or a numeric string, false otherwise.
Sometimes we need to cast a numerical value into another data type.
intval() function is often used to convert a value to an integer.
STEP 1: Read the value
STEP 2: Check if the value is an integer type
STEP 3: Check if the value is float or not
STEP 4: Check if the value is infinite or not
STEP 5: Check if the given value is not a number
STEP 6: Check if the given value is a number or not
STEP 7: Cast the given float number to an integer and display the value
<?php $x = 9988; var_dump($x); echo "\n"; $x = 12.368; var_dump($x); echo "\n"; $x = 2.8e411; var_dump($x); echo "\n"; $x = acos(2); var_dump($x); echo "\n"; $x = "3589"; var_dump(is_numeric($x)); echo "\n"; // Cast float to int $x = 58963.768; $int_cast = (int)$x; echo $int_cast;
int(9988) float(12.368) float(INF) float(NAN) bool(true) 58963