字符串到整数php的数组

sna*_*ken 7 php arrays string integer

我想将一个字符串(例如1,2,3,4,5,6)转换为php中的整数数组?我找到的函数只能访问字符串的第一个字符,例如1.如何将整个字符串转换为数组?

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;   


}
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 25

使用PHP的爆炸.

$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 );
Run Code Online (Sandbox Code Playgroud)

正如Tim Cooper所建议的,使用array_walk比上面的循环更简单:

array_walk($arr, 'intval');
Run Code Online (Sandbox Code Playgroud)

  • @Josh:你可以通过简单调用`array_walk`简化那个循环:`$ arr = array_walk('intval',$ arr);`. (2认同)

use*_*487 9

return array_map('intval', explode(",", '1,2,3,4,5,6,7,8,9'));
Run Code Online (Sandbox Code Playgroud)