Home > Article > Backend Development > How to force convert string to int type in php
php method to force a string to int type: 1. Use the intval() function to get the integer value of the variable, the syntax is "intval (string variable)"; 2. Use settype(), Variables can be set to a specified type with the syntax "settype(string variable, "integer")".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Method 2: Use intval() Function
intval() function is used to get the integer value of a variable.
<?php header("Content-type:text/html;charset=utf-8"); $str = '32.14abc'; $int = intval($str); echo $int."<br>"; echo '变量 $int 的类型为:' . gettype($int) . '<br>'; ?>
Description: The intval() function returns the integer value of the variable var by using the specified base conversion (the default is decimal). intval() cannot be used with object, otherwise an E_NOTICE error will be generated and 1 will be returned.
Method 3: Use the settype() function
settype ($var,$type)
The function can set the variable$var
Set to the specified type $type
, $type
Settable values:
"boolean" (or "bool", As of PHP 4.2.0)
"integer" (or "int" as of PHP 4.2.0)
"float " (Only available after PHP 4.2.0, "double" used in older versions is now deprecated)
"string"
"array"
"object"
"null" (from PHP 4.2.0)
Example:
<?php header("Content-type:text/html;charset=utf-8"); $str = '3542abc'; settype($str,"integer"); echo $str."<br>"; echo '修改后的类型为:' . gettype($str) . '<br>'; ?>
Description:
The settype() function changes the type of the variable itself.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to force convert string to int type in php. For more information, please follow other related articles on the PHP Chinese website!