How to convert php string to int array

PHPz
Release: 2023-04-26 09:33:56
Original
752 people have browsed it

In PHP, we can use various methods to convert a string into an array of integers.

A common way is to use the explode() function to split the string into arrays according to the specified delimiter, and then use the array_map() function to split each Elements are converted to integer types. As shown below:

$str = '1,2,3,4,5';
$arr = explode(',', $str);
$arr = array_map('intval', $arr);
Copy after login

Another way is to use regular expressions to extract the numbers in the string, and then use the array_map() function to convert each number to an integer type. As shown below:

$str = 'abc123def456ghi789';
preg_match_all('/\d+/', $str, $matches);
$arr = array_map('intval', $matches[0]);
Copy after login

You can also use the preg_split() function to split the string into arrays according to regular expressions, and then use the array_map() function to split each elements are converted to integer types. As shown below:

$str = 'a1b2c3d4e5';
$arr = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
$arr = array_map('intval', $arr);
Copy after login

Another way is to use the str_split() function introduced in PHP 7 to split the string into an array of individual characters and then use array_map( ) function converts each character to an integer type. As shown below:

$str = '12345';
$arr = str_split($str);
$arr = array_map('intval', $arr);
Copy after login

No matter which method is used, the string can eventually be converted into an integer array, which facilitates our subsequent processing.

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