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?

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.

If you'd like to make more memory available to your PHP script you can increase the available memory:

http://php.net/manual/en/ini.core.php#ini.memory-limit

You can make this change in the relevant php.ini config file, or during run-time by using ini_set with the memory_limit key.

If you need to increase your memory for one script only, you can use ini_set();

ini_set('memory_limit','16M');

Otherwise, you can increase your memory_limit in php.ini

memory_limit = 16M

Much simpler and what it's for:

$array = array_fill(1, 1000000, '');

This still fails at 2MB so change memory_limit to something higher probably 64MB at least.

Use range()

$arr = range(1,1000000);

But it still won't get around the fact that your memory limit is far too low to contain the size of array you want. There is no way around this. You're trying to dump a swimming pool's worth of water into a tea cup, and wondering why it's spilling everywhere.

This is more memory efficient than looping:

$array = array_fill_keys(range(1,1000000), '');

First increase your memory size. Then the most efficient way is to use SplFixedArray

It works with PHP >= 5.3.0

$array = new SplFixedArray(1000000);

In this way you have an array with NULL values.