Home  >  Article  >  Backend Development  >  How to convert php string to integer

How to convert php string to integer

藏色散人
藏色散人Original
2021-03-29 09:11:345269browse

How to convert PHP string to integer: 1. Force type conversion through "(int)$foo"; 2. Conversion through "intval($foo)" function; 3. Through "sprintf( "%d", $foo);" to convert.

How to convert php string to integer

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

Conversion method

In PHP , we can use 3 ways 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

Built-in function method is to use PHP’s built-in function intval to perform variable conversion operations.

The format of the intval function is: int intval(mixed $var [, int $base]);

3. Format string method

Format string method is to use %d of sprintf to format the specified variable to achieve the purpose of 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, and the intval function It is a typical process-oriented conversion, and forced type conversion more directly conveys the idea of ​​"I want to convert" to the reader. [Recommended learning: PHP video tutorial]

In terms of efficiency, forced type conversion is also the fastest conversion method (can directly obtain integer variable values ).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn