duanliaouu965826 2014-07-28 18:36
浏览 113
已采纳

PHP最好的方法是生成大型数组

I would like to generate a large array with a incremental key and empty value.

I tried:

$array = array();

for($i=1; $i <= 1000000; $i++)
   $array[$i] = '';

print_r($array);

thrown exception:

Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 131072 bytes)

What is the most efficient way?

  • 写回答

7条回答 默认 最新

  • dongwusang0314 2014-07-28 18:43
    关注

    To answer the title question, checkout the range function:

    $a = range(0,9);
    print_r($a);
    

    Output:

    Array
    (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] => 5
        [6] => 6
        [7] => 7
        [8] => 8
        [9] => 9
    )
    

    The issue you're having though is that you are running out of memory in php. Try increasing the memory limit if you really need an array that big.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?