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

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

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.

回答1:

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


回答2:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!