开发者

How to convert a comma separated string of numbers to an array of integers?

开发者 https://www.devze.com 2023-01-12 22:04 出处:网络
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?

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?

开发者_高级运维

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


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

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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号