如何将逗号分隔的数字字符串转换为整数数组?

时间:2022-04-08 00:17:31

Say I have the string 1,2,3,4,5 and I want to convert this to an array of integers - what would be the best way?

假设我有字符串1,2,3,4,5,我想将其转换为整数数组 - 最好的方法是什么?

I know I can use explode to create an array with the string but I need the array items to be integers.

我知道我可以使用explode来创建一个包含字符串的数组,但我需要将数组项作为整数。

2 个解决方案

#1


25  

You can use array_map to apply intval to each array item after you explode the string:

爆炸后,您可以使用array_map将intval应用于每个数组项:

$string = "1,2,3,4,5";
$int_array = array_map("intval", explode(",", $string));

#2


0  

You could also type cast it.

你也可以输入它。

$string = "1,2,3,4,5"; 
$explode = explode(',', $string);

foreach ($explode as $key)
$arrIntegers[] = (int) $key;


var_dump($arrIntegers);

#1


25  

You can use array_map to apply intval to each array item after you explode the string:

爆炸后,您可以使用array_map将intval应用于每个数组项:

$string = "1,2,3,4,5";
$int_array = array_map("intval", explode(",", $string));

#2


0  

You could also type cast it.

你也可以输入它。

$string = "1,2,3,4,5"; 
$explode = explode(',', $string);

foreach ($explode as $key)
$arrIntegers[] = (int) $key;


var_dump($arrIntegers);