Home>Article>Backend Development> php convert string to int type

php convert string to int type

藏色散人
藏色散人 Original
2020-08-08 09:42:27 6428browse

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.

php convert string to int type

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.

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]); (摘自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.

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!

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