This article mainly compares the functions and definitions of intval()
type conversion and (int)
forced type conversion with some examples to distinguish between the two.
1.intval() function
Syntax:
intval ( mixed $value , int $base = 10 ) : int
value
is the quantity value to be converted into integer
base
is the base used for conversion (not Default is decimal)
Return value: int
type variable
PS: Unless value
is a string, otherwise base
will not work.
Example:
<?php echo intval(42)."<br>"; // 42 echo intval(4.2)."<br>"; // 4 echo intval('42')."<br>"; // 42 echo intval('+42')."<br>"; // 42 echo intval('-42')."<br>"; // -42 echo intval(042)."<br>"; // 34 echo intval('042')."<br>"; // 42 echo intval(1e10)."<br>"; // 1410065408 echo intval('1e10')."<br>"; // 1 echo intval(0x1A)."<br>"; // 26 echo intval(42000000)."<br>"; // 42000000 echo intval(420000000000000000000)."<br>"; // 0 echo intval('420000000000000000000')."<br>"; // 2147483647 echo intval(42, 8)."<br>"; // 42 echo intval('42', 8)."<br>"; // 34 echo intval(array())."<br>"; // 0 echo intval(array('foo', 'bar'))."<br>"; // 1 echo intval(false)."<br>"; // 0 echo intval(true)."<br>"; // 1 ?>
2. (int) forced conversion
Demonstration :
<?php echo (int)42; // 42 echo "<br>"; echo (int)4.2; // 4 echo "<br>"; echo (int)'42'; // 42 echo "<br>"; echo (int)'+42'; // 42 echo "<br>"; echo (int)'-42'; // -42 echo "<br>"; echo (int)042; // 34 echo "<br>"; echo (int)'042'; // 42 echo "<br>"; echo (int)1e10; // 1410065408 echo "<br>"; echo (int)'1e10'; //2147483647 echo "<br>"; echo (int)0x1A; // 26 echo "<br>"; echo (int)42000000;// 42000000 echo "<br>"; echo (int)420000000000000000000; //-1609564160 echo "<br>"; echo (int)'420000000000000000000'; //2147483647 echo "<br>"; /*echo intval(42, 8)."<br>"; echo intval('42', 8)."<br>"; */ /*int的强制转换不是函数,所以无法实现*/ echo (int)array();// 0 echo "<br>"; echo (int)array('foo', 'bar');//1 echo "<br>"; echo (int)false; //0 echo "<br>"; echo (int)true; //1 echo "<br>"; ?>
3. Summary:
##int forced conversion and
The intval() function remains consistent when facing
boolean,
int,
float,
array (not exceeding each the maximum value displayed for each type).
intval()If the parameter is a string, returns the integer value represented by the digit string before the first character in the string that is not a digit. If the first character in the string is ‘-’, counting starts from the second character. If the parameter is a dotted number, its rounded value is returned.
The maximum value of the int type is
2147483647Generally during type conversion, if the maximum value is exceeded, the maximum value is displayed,
( int) will display
-1609564160.
The above is the detailed content of How to distinguish between intval() and (int) in PHP. For more information, please follow other related articles on the PHP Chinese website!