String to array of Integers php

后端 未结 5 2007
攒了一身酷
攒了一身酷 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

    Use PHP's explode.

    $str = "1,2,3,4,5,6";
    $arr = explode("," $str); // array( '1', '2', '3', '4', '5', '6' );
    
    foreach ($arr AS $index => $value)
        $arr[$index] = (int)$value; 
    
    // casts each value to integer type -- array( 1, 2, 3, 4, 5, 6 );
    

    As suggested by Tim Cooper, using array_walk is simpler than the above loop:

    array_walk($arr, 'intval');
    
    0 讨论(0)
  • 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)
        }
        }
    */
    
    0 讨论(0)
  • 2020-12-07 02:32
    return array_map('intval', explode(",", '1,2,3,4,5,6,7,8,9'));
    
    0 讨论(0)
  • 2020-12-07 02:34
    explode(",",'1,2,3,4,5,6,7,8,9');
    

    http://www.php.net/manual/en/function.explode.php

    0 讨论(0)
  • 2020-12-07 02:46

    You can use http://pl.php.net/manual/en/function.explode.php

    0 讨论(0)
提交回复
热议问题