Home > Article > Backend Development > Three ways to convert string to integer type in php
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
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
(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
2. Type conversion
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
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
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
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!