Home » Php » String to array of Integers php

String to array of Integers php

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.
How can I conert the whole string to array?

function read_id_txt()
{

        $handle_file = fopen("temporalfile.txt", 'r'); 

        $i=0;

        while ($array_var[$i] = fgets($handle_file, 4096)) { 
            echo "<br>";
            print_r($array_var[i]);
            $i++;
        }

        fclose($handle_file);   

        $temp=explode(" ", $array_var[0]);      

        return $temp;   


}
How to&Answers:

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

Answer:

return array_map('intval', explode(",", '1,2,3,4,5,6,7,8,9'));

Answer:

explode(",",'1,2,3,4,5,6,7,8,9');

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

Answer:

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)
    }
    }
*/

Answer:

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