PHP: maximum array length (size)

Arrays are great way to store and manipulate data. But how big array can be? While there aren’t any limitations from PHP side, your server’s memory will limit size of array.
Easiest way to test this is by creating array that consists of 1000 numbers:

$arr = range(1, 1000);

So far so good…
What if we take it up a notch? Say 10 000 000?
Unless you’re running server on alien spaceship, this will result in error

Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 32 bytes) in

Increase memory limit.

Add this to beginning of PHP code:

ini_set('memory_limit', '1500M');
You can’t set this higher than free memory your server has. Be extra careful on production server as too high limit may crash it.

How high should memory_limit be? It depends on size of array and version of PHP (newer versions require less memory). For example on PHP 7 generating array of 10 000 000 consecutive numbers on my local server requires 1348,75 MB memory

You can measure used memory using memory_get_usage() function

Many keys, short value
I generated veeeeeeery long array.

for ($i=0; $i<30000000; $i++) {

With PHP 7 that took 1026 MB. I honesty don’t want to try PHP 5.6
Few keys, long values
I generated 10 Lorem Ipsum files, each 122MB of size.
Then I created this crazy array.

$arr = array();
for ($i = 0; $i < 10; $i++) {
	$content = file_get_contents("content{$i}.txt");
	$arr[$i]= $content;

On PHP 7 that took 1240 MB memory, which is only slightly larger than filesize of all txt files.

Upgrade PHP version

As mentioned above, in never version you can make larger arrays using
same amount of memory. Not only PHP 7 requires much less memory than PHP 5.6, time of execution also is significantly better.
[@TODO Here will be link how to upgrade to PHP 7]

Store data differently

Apart from splitting huge array in smaller ones, you can use MultipartCache class :

In summary, only limit of array’s size is your server’s RAM. Try increasing it, upgrade to newer PHP version or use arrays in smarter way.

Deprecated: Non-static method dc_jqslicksocial::footer() should not be called statically in /var/www/ on line 298

Notice: Undefined index: show_post in /var/www/ on line 805