I am trying to create a 2D array in PHP with a size of 2000x2000 (4 million entries). It seems that I run out of memory here, but the manner in which the error is appearing is confusing me.
When I define the array and fill it initially using the array_fill command, and initialize each position in the array (matrix) with 0 there is no problem.
However if I try iterating over the array and fill each position with 0, it runs out of memory.
I would assume that once I run array_fill it allocates the memory at that point, and it should not run out of memory in the loop.
Of course, this is just a simplified version of the code. In my actual application I will be using the X & Y coordinates to lookup value from another table, process it, and then store it in my matrix. These will be floating point values.
Can somebody help through some light on this please? Is there some other way I should be doing this?
Thank you!
<?php
// Set error reporting.
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
// Define Matrix dimensions.
define("MATRIX_WIDTH", 2000+1);
define("MATRIX_HEIGHT", 2000+1);
// Setup array for matrix and initialize it.
$matrix = array_fill(0,MATRIX_HEIGHT,array_fill(0,MATRIX_WIDTH,0));
// Populate each matrix point with calculated value.
for($y_cood=0;$y_cood<MATRIX_HEIGHT;$y_cood++) {
// Debugging statement to see where the script stops running.
if( ($y_cood % 100) == 0 ) {print("Y=$y_cood<br>"); flush();}
for($x_cood=0;$x_cood<MATRIX_WIDTH;$x_cood++) {
$fill_value = 0;
$matrix[$y_cood][$x_cood]=$fill_value;
}
}
print("Matrix width: ".count($matrix)."<br>");
print("Matrix height: ".count($matrix[0])."<br>");
?>

memory_limit = 128M ; Maximum amount of memory a script may consume (128MB). I personally do not advise to believe the results which caused by unstable script behavior.