Home > Backend Development > PHP Problem > php convert string to int type

php convert string to int type

藏色散人
Release: 2023-03-04 06:42:01
Original
6553 people have browsed it

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.

<?php 
$foo = "1"; // $foo 是字符串类型 
$bar = (int)$foo; // $bar 是整型 
?>
Copy after login

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 是整型 
?>
Copy after login

The format of the intval function is:

int intval(mixed $var [, int $base]); (摘自PHP手册)
Copy after login

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
Copy after login

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 是字符串类型 
?>
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template