Home > Article > Backend Development > What is the difference between intval() and int cast in php?
The difference between intval() and int cast under php is: 1. [intval()] If the parameter is a string, return the number string before the first character in the string that is not a number. The integer value represented; 2. Convert the PHP string to int, just convert it before use.
The difference between intval() and int cast under php is
PHP string conversion For intval()
intval()
, if the parameter is a string, return the string of digits before the first character in the string that is not a digit. Integer value. If the first character in the string is ‘-’, counting starts from the second character.
If the parameter is a dot number, its rounded value is returned.
Of course, the value returned by intval() is within the range that can be represented by a 4-byte value (-2147483648~2147483647). Values exceeding this range will be replaced by boundary values.
Example:
intval("A")=0; intval(12.3223)=12; intval("1123Asdfka3243")=1123;
Example:
$a=0.13; $b=(int)$a; //$b=0; $a=0.99; $b=(int)$a; //$b=0; $a=1.01; $b=(int)$a; //$b=1; $a=1.99; $b=(int)$a; //$b=1;
PHP string to int
Sometimes, it’s important to have an int The value of the format variable. eaxmple, if your visitor fills out the form with the age field, this should be an int. However, in the
$_POST
array, you are treating it as a string.
Converting a PHP string to int is easy. We need to use your variable type before casting.So
you need to use (INT). Here is an example of how to do this:
The code is as follows:
<?php $str = "10"; $num = (int)$str;?>
If you want to check that the code REALY works, we can use the === operator. This operator checks not only the value, but the type as well. Such code should look like this:
The code is as follows:
<?php $str = "10"; $num = (int)$str; if ($str === 10) echo "String"; if ($num === 10) echo "Integer"; ?>
Related learning recommendations:PHP programming from entry to proficiency
The above is the detailed content of What is the difference between intval() and int cast in php?. For more information, please follow other related articles on the PHP Chinese website!