Home>Article>Backend Development> How to convert string to number in php
4 conversion methods: 1. Use the intval() function to convert, the syntax is "intval($val)"; 2. Use the settype() function to convert, the syntax is "settype($val,"integer")" ; 3. Add the target type "(int)" enclosed in parentheses before the variable, the syntax "(int)$val"; 4. Use the " " operator to add the string and the number 0, the syntax "$val" 0".
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php will value Forced to a numeric type
#Method 1: 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.
"; $int = intval($str); echo $int."
"; echo '变量 $int 的类型为:' . gettype($int) . '
'; echo '
'; $str = 'abc123.456'; echo $str."
"; $int = intval($str); echo $int."
"; echo '变量 $int 的类型为:' . gettype($int) . '
'; echo '
'; $str = '123.abc456'; echo $str."
"; $int = intval($str); echo $int."
"; echo '变量 $int 的类型为:' . gettype($int) . '
'; ?>
Note: When using the intval() function to convert a string to a number, you can only extract the number before the character. If it starts with a letter, the number extracted is 0.
Method 2: Use the settype() function
"; settype($str,"integer"); echo $str."##Description: settype() function is used to The variable $var is set to the specified $type type. Syntax:
"; echo '修改后的类型为:' . gettype($str) . '
'; echo '
'; $str = 'abc123.456'; echo $str."
"; settype($str,"integer"); echo $str."
"; echo '修改后的类型为:' . gettype($str) . '
'; ?>
settype ( $var ,$type )$type Settable values:
"; echo '变量 $int 的类型为:' . gettype($int) . 'Method 4: Use " " operator to add string and number 0
'; ?>
"; $int = $str+0; echo $int."
"; echo '变量 $int 的类型为:' . gettype($int) . '
'; ?>
Because PHP is weakly typed Languages that perform invisible numeric type conversion.
Recommended learning: "
PHP Video TutorialThe above is the detailed content of How to convert string to number in php. For more information, please follow other related articles on the PHP Chinese website!