Home > Article > Backend Development > What are the methods in php to convert string type to int type?
php methods to convert string type to int type are: 1. Forced type conversion method; 2. Built-in function method; 3. Format string method. The forced type conversion method refers to adding the target type enclosed in parentheses before the variable to be converted, such as [(int)$var].
Specific method:
(Video tutorial recommendation: php video tutorial)
1. Forced type conversion method
Forced type conversion method is the method of "adding the target type enclosed in parentheses before the variable to be converted" (extracted from the "Type Tricks" section of the PHP manual).
<?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 是整型 ?>
3. Formatted 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."
Related recommendations: php training
The above is the detailed content of What are the methods in php to convert string type to int type?. For more information, please follow other related articles on the PHP Chinese website!