Home > Article > Backend Development > How to force value to numeric type in php
Conversion method: 1. Add the target type "(int)" enclosed in parentheses before the variable, the syntax "(int)$val"; 2. Use the intval() function, the syntax "intval( $val)"; 3. Use settype(), the syntax is "settype($val,"integer")".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php forces the value Convert to numeric type
#Method 1: Add the target type "(int)" or "(integer)" enclosed in parentheses before the variable to be converted
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $int = (int)$str; echo $int."<br>"; echo '变量 $int 的类型为:' . gettype($int) . '<br>'; ?>
Method 2: Use the specific conversion function intval()
intval() function is used to obtain the integer of the variable value.
intval() function returns the integer value of variable var by using the specified base conversion (default is decimal). intval() cannot be used with object, otherwise an E_NOTICE error will be generated and 1 will be returned.
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $int = intval($str); echo $int."<br>"; echo '变量 $int 的类型为:' . gettype($int) . '<br>'; ?>
Method 3: Use the settype() function
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; settype($str,"integer"); echo $str."<br>"; echo '修改后的类型为:' . gettype($str) . '<br>'; ?>
Instructions:
The settype() function is used to set the variable $var to the specified $type type. Syntax:
settype ( $var ,$type )
$type Settable values:
"boolean" (or "bool", starting from PHP 4.2.0)
"integer" (or "int" since PHP 4.2.0)
"float" (only available since PHP 4.2.0, For "double" used in older versions now deprecated)
"string"
"array"
"object"
PHP Video Tutorial"
The above is the detailed content of How to force value to numeric type in php. For more information, please follow other related articles on the PHP Chinese website!