Two-Dimensional Array Searching in PHP

Tested with PHP 5.3.1

PHP’s array_search function is great! No longer must we single-step through every element of an array to find what we’re looking for. Too bad it only works on single-dimension arrays.

$array = array(5, 10, 15, 20, 25);
/* $array contents
[0]	[1]	[2]	[3]	[4]
5	10	15	20	25
*/
$found = array_search(20, $array);
/* $found contents
3
*/
for ($y = 0; $y < 5; $y++) {
	for ($x = 0; $x < 5; $x++) {
		$array2[$x][$y] = 0;
		if (($x == 1 && $y == 1) || ($x == 2 && $y == 1) || ($x == 1 && $y == 2) || ($x == 2 && $y == 2)) $array2[$x][$y] = 1;
	}
}
/* $array2 contents
	[0]	[1]	[2]	[3]	[4]
[0]	0	0	0	0	0
[1]	0	1	1	0	0
[2]	0	1	1	0	0
[3]	0	0	0	0	0
[4]	0	0	0	0	0
*/
$found2 = array_search(1, $array2);
/* $found2 contents
FALSE
*/

Happily, there is a fairly easy way to deal with this in PHP. All you need to know is that a two-dimensional array is an array of arrays.

/* $array2[0] contents
[0]	[1]	[2]	[3]	[4]
0	0	0	0	0

$array2[1] contents
[0]	[1]	[2]	[3]	[4]
0	1	1	0	0
etc*/

So, in order to use array_search, we simply need to search the second array contained within the first array. If we keep track of where we are, we’ll have both the keys we need (the one we kept track of, and the one returned by array_search).

unset($x, $y); // starting over with both variables, just in case
$search = 1; // what we're looking for
for ($x = 0; $x < 5; $x++) { // hunting through the array with $x, which will also be one of our 2D keys
	$y = array_search($search, $array2[$x]); // $y will be our second 2D key
	if (is_int($y)) break; // did we find it? if so, hooray! $y is our second key. let's get out of here
}
/* $x $y contents
$x	$y
1	1
*/

Using this method, it will search first from left to right, move down, and repeat. A bit like reading a book. There isn’t much error checking here, so I wouldn’t copy it line for line, if I were you. A similar method could likely drill through three- or more dimensional arrays, however, having grown up in the 16-bit era of video games, I’m really only good at thinking in 2D.

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>

 

Trackbacks and Pingbacks: