Home > Backend Development > PHP Problem > How to convert array into int array in php

How to convert array into int array in php

PHPz
Release: 2023-04-25 14:10:32
Original
536 people have browsed it

PHP language provides many functions to operate arrays, including functions that convert string array types into integer array types. This function can be used to convert string arrays into integer arrays. .

In PHP, you can use the array_map() function to convert the string type in the string array into an integer type. The syntax of the array_map() function is as follows:

array array_map(callable $callback, array $array1 [, array $... ]);
Copy after login

Among them, $callback is a callback function, which can pass in each element in the array and then process each element; and $array1 [, array $... ] is the array to be converted.

The sample code for using the array_map() function to convert a string array into an integer array is as follows:

<?php
$array = array("1", "2", "3", "4", "5");
$new_array = array_map(&#39;intval&#39;, $array); // 将字符串数组转化成整型数组
print_r($new_array);
?>
Copy after login

In the above code, the string is converted into an integer type by using the intval() function number, and then use the array_map() function to store the integer number into $new_array. Use the print_r() function to output a new integer array.

In addition to using the array_map() function, you can also use the foreach loop to convert a string array into an integer array. The code example is as follows:

<?php
$array = array("1", "2", "3", "4", "5");
$new_array = array(); // 定义新的整型数组
foreach ($array as $value) {
    $new_array[] = intval($value); // 将字符串转化成整型数,存储到新数组中
}

print_r($new_array);
?>
Copy after login

To summarize, you can use array_map() or foreach loop in PHP to convert an array of string type into an array of integer type. It should be noted that when using these functions, each element needs to be processed the same.

The above is the detailed content of How to convert array into int array 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