How to convert PHP string to integer: 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 formats the specified variables and so on.
Recommendation: "PHP Video Tutorial"
PHP Convert string to integer
Conversion methods
In PHP, we can use 3 methods to convert strings into integers.
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".
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.
The format of the intval function is: int intval(mixed $var [, int $base]);
3. Format string method
Format string The method is to use sprintf's %d to format the specified variable to achieve type conversion.
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."
Performance
int > intval > sprintf
From the perspective of readability, the sprintf method code is relatively long, and the result may need to be forced type conversion again, while the intval function is a typical procedure-oriented method Conversion and forced type conversion more directly convey the idea of "I want to convert" to the reader.
In terms of efficiency, forced type conversion is also the fastest conversion method (the integer variable value can be obtained directly).
The above is the detailed content of How to convert php string to integer. For more information, please follow other related articles on the PHP Chinese website!