This is one of those problems that is probably best solved by just writing some code.
function processPixel($pixeLeft, $pixelMiddle, $pixelRight, $pixelAbove, $rowBelow)
{
//Whatever it is you're doing.
}
function processRow($rowAbove, $rowMiddle, $rowBelow)
{
for ($x = 0; $x < count($pixels); $x++) {
$pixelAbove = null;
$pixelBelow = null;
$pixeLeft = null;
$pixelRight = null;
$pixelMiddle = $pixels[0];
if (($x - 1) >= 0) {
$pixelLeft = $pixels[$x - 1];
}
if (($x + 1) < count($pixels)) {
$pixelRight = $pixels[$x + 1];
}
if ($rowAbove != null) {
$pixelAbove = $rowAbove[$x];
}
if ($rowBelow != null) {
$rowBelow = $rowBelow[$x];
}
processPixel($pixeLeft, $pixelMiddle, $pixelRight, $pixelAbove, $rowBelow)
}
}
function processImageIterator($imageIterator)
{
$rowAbove = null;
$rowMiddle = null;
$rowBelow = null;
foreach ($imageIterator as $rowPixels) {
$rowBelow = $rowPixels;
foreach ($imageIterator as $rowPixels) {
processRow($rowAbove, $rowMiddle, $rowBelow);
}
$rowAbove = $rowMiddle;
$rowMiddle = $rowBelow;
}
// Finish last row with middle on the last row
processRow($rowAbove, $rowMiddle, null);
//Finish row of pixel below last row. This may not be necessary
//depending on your algorithm,
$rowAbove = $rowMiddle;
processRow($rowAbove, null, null);
}
Just to note, this will be highly non-performant, aka slow as heck. It may (but not guaranteed) be faster to implement whatever it is you're trying to do as an FX operator. Example here and full documentation here.