Scaling/Blowing Up a Two-Dimensional Array in PHP

Tested with PHP 5.3.1

In an upcoming post (Sightlines, or: Drawing Virtual Lines in a Two-Dimensional PHP Array Using Bresenham’s Line Algorithm), I’ll explain why I need to scale/blow up an array to 10x it’s size. Until then, this code snippet might not seem so useful. But, most everything I have written thus far has been leading up to the aforementioned post, and this is certainly a part of it.

$width = 5; // the size of the x-axis of the original array
$height = 5; // and the y-axis
for ($y = 0; $y < $height; $y++) { // creates a 5x5 array...
	for ($x = 0; $x < $width; $x++) { // ...and fills it with a checkerboard...
		$array1[$x][$y] = (is_float(($x + $y) / 2)) ? 0 : 1; // ...of ones and zeroes
	}
}
/* $array1 contents
	[0]	[1]	[2]	[3]	[4]
[0]	1	0	1	0	1
[1]	0	1	0	1	0
[2]	1	0	1	0	1
[3]	0	1	0	1	0
[4]	1	0	1	0	1
*/
$multi = 2; // how much larger the array will be--in this case, 2x larger
$x_multi = 0; // keeps track of where we are on the x-axis
$y_multi = 0; // and the y-axis
for ($y = 0; $y < $height; $y++) { // runs through our orignial array
	for ($x = 0; $x < $width; $x++) {
		for ($row = 0; $row < $multi; $row++) { // setting up our new, larger array
			for ($col = 0; $col < $multi; $col++) {
				$array2[$col + $x_multi][$row + $y_multi] = $array1[$x][$y]; // populates the new array with the old array's values
			}
		}
		$x_multi += $multi; // starting a new column
		if ($x_multi >= (($width) * $multi)) $x_multi = 0; // if it's our last column, resets the column to 0...
	}
	$y_multi += $multi; // ...because we're starting a new row
}
/* $array2 contents
	[0]	[1]	[2]	[3]	[4]	[5]	[6]	[7]	[8]	[9]
[0]	1	1	0	0	1	1	0	0	1	1
[1]	1	1	0	0	1	1	0	0	1	1
[2]	0	0	1	1	0	0	1	1	0	0
[3]	0	0	1	1	0	0	1	1	0	0
[4]	1	1	0	0	1	1	0	0	1	1
[5]	1	1	0	0	1	1	0	0	1	1
[6]	0	0	1	1	0	0	1	1	0	0
[7]	0	0	1	1	0	0	1	1	0	0
[8]	1	1	0	0	1	1	0	0	1	1
[9]	1	1	0	0	1	1	0	0	1	1
*/

Now we have an array that is twice as large as it was previously, and the values have scaled accordingly.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>