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.
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; echo $str."<br>"; $int = intval($str); echo $int."<br>"; echo '变量 $int 的类型为:' . gettype($int) . '<br>'; echo '<hr>'; $str = 'abc123.456'; echo $str."<br>"; $int = intval($str); echo $int."<br>"; echo '变量 $int 的类型为:' . gettype($int) . '<br>'; echo '<hr>'; $str = '123.abc456'; echo $str."<br>"; $int = intval($str); echo $int."<br>"; echo '变量 $int 的类型为:' . gettype($int) . '<br>'; ?>
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
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; echo $str."<br>"; settype($str,"integer"); echo $str."<br>"; echo '修改后的类型为:' . gettype($str) . '<br>'; echo '<hr>'; $str = 'abc123.456'; echo $str."<br>"; settype($str,"integer"); echo $str."<br>"; echo '修改后的类型为:' . gettype($str) . '<br>'; ?>
settype ( $var ,$type )
<?php
header("Content-type:text/html;charset=utf-8");
$str = '123.456abc';
$int = (int)$str;
echo $int."<br>";
echo '变量 $int 的类型为:' . gettype($int) . '<br>';
?>
Because PHP is weakly typed Languages that perform invisible numeric type conversion. Recommended learning: " The 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!<?php
header("Content-type:text/html;charset=utf-8");
$str = '123abc';
echo $str."<br>";
$int = $str+0;
echo $int."<br>";
echo '变量 $int 的类型为:' . gettype($int) . '<br>';
?>