Three ways to convert string to integer type in php

PHPz
Release: 2023-04-03 13:36:02
Original
1552 people have browsed it

There are multiple methods provided in the PHP language to convert strings to integer types. This article will introduce PHP built-in functions, type conversions and custom methods to convert strings to integer types.

1. PHP built-in function

  1. intval() function

intval() function can convert a string to an integer type and return the integer value. If conversion to an integer type is not possible, 0 is returned.

Sample code:

$num1 = "1234";
$num2 = "56.78";
$num3 = "hello";
 
// 字符串转换为整数类型
echo intval($num1); // 输出:1234
echo intval($num2); // 输出:56
echo intval($num3); // 输出:0
Copy after login
  1. (int) forced type conversion

(int) can convert a string to an integer type. If it cannot be converted, Then return 0.

Sample code:

$num1 = "1234";
$num2 = "56.78";
$num3 = "hello";
 
// 字符串转换为整数类型
echo (int)$num1; // 输出:1234
echo (int)$num2; // 输出:56
echo (int)$num3; // 输出:0
Copy after login

2. Type conversion

  1. Addition operator

Add a string to 0, you can Convert a string to an integer type.

Sample code:

$num1 = "1234";
$num2 = "56.78";
$num3 = "hello";
 
// 字符串转换为整数类型
echo $num1 + 0; // 输出:1234
echo $num2 + 0; // 输出:56
echo $num3 + 0; // 输出:0
Copy after login
  1. Use (int) cast in the array

Use (int) cast to convert each element in the array , which converts string elements into integer elements.

Sample code:

$arr = array("1234", "56.78", "hello");
 
// 数组元素转换为整数类型
foreach ($arr as $value) {
    echo (int)$value . " ";
}
// 输出:1234 56 0
Copy after login

3. Custom method

If the above method cannot meet the needs, you can also customize a method to convert the string to an integer type.

Sample code:

function strToInt($str) {
    $len = strlen($str); // 获取字符串长度
    $num = 0; // 定义初始值为0
    for ($i = 0; $i < $len; $i++) { // 循环处理每个字符
        $num = $num * 10 + ord($str{$i}) - ord('0'); // 将字符转换为数字,并加入结果中
    }
    return $num; // 返回结果
}
 
// 字符串转换为整数类型
echo strToInt("1234"); // 输出:1234
Copy after login

The above is how to convert strings in PHP to integer types. If you need to convert the string to another type, you can also use a similar method.

The above is the detailed content of Three ways to convert string to integer type in php. For more information, please follow other related articles on the PHP Chinese website!

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