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

后端 未结 2 1911
温柔的废话
温柔的废话 2021-01-18 02:51

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 a

相关标签:
2条回答
  • 2021-01-18 02:56

    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 讨论(0)
  • 2021-01-18 03:00

    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));
    
    0 讨论(0)
提交回复
热议问题