Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to array of Integers php

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;   


}
like image 605
snake plissken Avatar asked Jan 22 '12 19:01

snake plissken


1 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');
like image 60
Josh Avatar answered Oct 03 '22 19:10

Josh