I have a 3×3 matrix in PHP:
2 4 6
5 4 7
8 5 7
Assuming I am on the [0,0] element so 2. What is the best way to store where I am in the multi-dimensional array in a variable $current? I am thinking pointer, but not sure how to do this in PHP.
$current = $data[0][0];
Does not help, because it doesn’t store context.
Secondly, what the best way to then code looking (peeking) right, down, left, and up assuming $current is stored?
Thanks.
There are no pointers in PHP, and you wouldn’t be able to do pointer arithmetics on references.
You can use the
next()andprev()functions to go forward and backwards in an array and you can usekey()to find out where you are.current()will return the value stored at the current position in the array (kind of like dereferencing the pointer).These all work on a single level of depth, so you can’t find the position in a multidimensional array.
The best way of working with multidimensional arrays is likely simply storing and incrementing / decrementing the X and Y values that identify a position in the array. Since arrays in PHP are implemented internally as hashes, referencing
$data[$x][$y]is very fast, regardless of what$xand$ycontain.For example, if your current position in the matrix is (1, 1), you could have a variable storing this:
To find out what’s stored there, look it up:
To find out what’s stored at the upper-left side of this position, you could obtain the position by simply subtracting 1 from the current position’s coordinates, then looking up that position: