I am trying to create a 2D array in PHP of 2000x2000 size (4 million records). It seems like I'm running out of memory, but the way the error appears is confusing to me.
When I define an array and fill it first using the array_fill command, and initialize each position in the array (matrix) with 0, there is no problem.
However, if I try to iterate through an array and fill each position with 0, it runs out of memory.
I would suggest that when I run array_fill, it allocates memory at this point and should not exit memory in a loop.
Of course, this is just a simplified version of the code. In my actual application, I will use the X and Y coordinates to find the value from another table, process it, and then save it in my matrix. These will be floating point values.
Can someone help through some light on this please? Is there any other way I have to do this?
Thanks!
<?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>"); ?>
source share