String to array of Integers php

后端 未结 5 2028
攒了一身酷
攒了一身酷 2020-12-07 01:47

I wan to convert a string for example 1,2,3,4,5,6 to an array of integers in php? I find functions that only have access to the first character of the string for example 1.

5条回答
  •  悲哀的现实
    2020-12-07 02:25

    The above answers could potentially return non-numeric values

    array_walk & array_map with intval

    Both return arrays that are tainted with non-numeric values.

    $string = ',g,6,4,3,f,32,a,';
    $array = explode(',', $string);
    array_walk($array, 'intval');
    $arrayMap = array_map('intval', $array);
    var_dump($array);
    var_dump($arrayMap);
    /*
         array(9) {
          [0]=>
          string(0) ""
          [1]=>
          string(1) "g"
          [2]=>
          string(1) "6"
          [3]=>
          string(1) "4"
          [4]=>
          string(1) "3"
          [5]=>
          string(1) "f"
          [6]=>
          string(2) "32"
          [7]=>
          string(1) "a"
          [8]=>
          string(0) ""
        }
     */
    

    array_filter to only return numeric values

    $string = ',g,6,4,3,f,32,a,';
    $array = explode(',', $string);
    $numericOnlyArray = array_filter($array,'is_numeric');
    
    var_dump($numericOnlyArray);
    
    /*
        result:
        array(4) {
          [2]=>
          string(1) "6"
          [3]=>
          string(1) "4"
          [4]=>
          string(1) "3"
          [6]=>
          string(2) "32"
        }
    */
    

    To get only integers

    $string = ',g,6,4,3,f,32,a,';
    $array = explode(',', $string);
    $result = array_map('intval', array_filter($array, 'is_numeric'));
    
    var_dump($result);
    
    /*
        result:
        array(4) {
          [2]=>
          int(6)
          [3]=>
          int(4)
          [4]=>
          int(3)
          [6]=>
          int(32)
        }
        }
    */
    

提交回复
热议问题