Simone Nigro
Simone Nigro

Reputation: 4887

PHP best way generate large array

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?

Upvotes: 0

Views: 1427

Answers (7)

AbraCadaver
AbraCadaver

Reputation: 78994

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.

Upvotes: 1

c-griffin
c-griffin

Reputation: 3026

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

Upvotes: 0

bitWorking
bitWorking

Reputation: 12665

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.

Upvotes: 1

Dave
Dave

Reputation: 3658

This is more memory efficient than looping:

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

Upvotes: 1

Marc B
Marc B

Reputation: 360762

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.

Upvotes: 1

Jeff Lambert
Jeff Lambert

Reputation: 24661

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.

Upvotes: 1

oliakaoil
oliakaoil

Reputation: 1699

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.

Upvotes: 0

Related Questions