Home > Article > Backend Development > php convert string to int type
php method to convert a string into an int type: 1. Add the target type enclosed in parentheses before the variable to be converted; 2. Use PHP's built-in function intval to convert the variable; 3. , Use sprintf's "%d" to format the specified variable.
Recommended: "PHP Video Tutorial"
In PHP, we can use 3 ways to convert strings Convert to integer.
1. Forced type conversion method
Forced type conversion method is to "add the target type enclosed in parentheses before the variable to be converted" (extracted from the "Type Tricks" section of the PHP manual )The way.
<?php $foo = "1"; // $foo 是字符串类型 $bar = (int)$foo; // $bar 是整型 ?>
For integers, the cast type name is int or integer.
2. Built-in function method
The built-in function method uses PHP’s built-in function intval to convert variables.
<?php $foo = "1"; // $foo 是字符串类型 $bar = intval($foo); // $bar 是整型 ?>
The format of the intval function is:
int intval(mixed $var [, int $base]); (摘自PHP手册)
Although the PHP manual clearly states that intval() cannot be used for conversion of array and object. But after my testing, there will be no problems when converting the array. The converted value is 1, not 0 as expected. I'm afraid it's because within PHP, array type variables are also considered to have non-zero values. When converting object, PHP will give the following notice:
Object of class xxxx could not be converted to int in xxxxx.php on line xx
The conversion value is also 1.
3. Format string method
The formatted string method uses sprintf's %d to format the specified variable to achieve the purpose of type conversion.
<?php $foo = "1"; // $foo 是字符串类型 $bar = sprintf("%d", $foo); // $bar 是字符串类型 ?>
Strictly speaking, the conversion result of sprintf is still string type, so it should not be regarded as a way to convert strings into integers. But the string value after his processing has indeed become "an integer that is forced to be converted to a string type."
The above is the detailed content of php convert string to int type. For more information, please follow other related articles on the PHP Chinese website!