Two-Dimensional Array Slicing in PHP

Tested with PHP 5.3.1

The array_slice function in PHP is a handy way to copy a chunk of information from one array to second array. This is useful to examine or modify some interesting set of data without mucking about with your original set, or cutting down on the size and overhead of operations, because you’re running them against a more compact array.

The function works on two-dimensional arrays, but in an unexpected way.

$array1 = array(5, 10, 15, 20, 25);
/* $array1 contents
[0]	[1]	[2]	[3]	[4]
5	10	15	20	25
*/
$array2 = array_slice($array1, 2);
/* $array2 contents
[0]	[1]	[2]
15	20	25
*/
for ($y = 0; $y < 5; $y++) {
	for ($x = 0; $x < 5; $x++) {
		$array3[$x][$y] = $x * $y;
	}
}
/* $array3 contents
	[0]	[1]	[2]	[3]	[4]
[0]	0	0	0	0	0
[1]	0	1	2	3	4
[2]	0	2	4	6	8
[3]	0	3	6	9	12
[4]	0	4	8	12	16
*/
$array4 = array_slice($array3, 2);
/* $array4 contents
	[0]	[1]	[2]
[0]	0	0	0
[1]	2	3	4
[2]	4	6	8
[3]	6	9	12
[4]	8	12	16
*/

As you can see above, you can control the size of the x-axis when slicing data, but not the y-axis.

The solution to this problem is very similar to my previous post, Two-Dimensional Array Searching in PHP. Namely, if we keep in mind that a 2D array is an array of arrays, we can simply step through the x-axis array and slice from the y-axis to get the size we want.

$x_offset = 2; // how far in on the x-axis we want to start the slice
$y_offset = 2; // ...and on the y-axis
$width = 3; // how big is the x-axis
$height = 3; // how big is the y-axis
for ($x = 0; $x < $width; $x++) { // stepping through the x-axis
	$array5[$x] = array_slice($array3[$x_offset + $x], $y_offset, $height); // pulling out the y-axis and stuffing it in a new array
}
/* $array5 contents
	[0]	[1]	[2]
[0]	4	6	8
[1]	6	9	12
[2]	8	12	16
*/

Now we’re able to control the size in both dimensions. As with before, there is no error-checking in this–make sure you don’t go out of bounds on those arrays, kids!

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>