Skip to content

Instantly share code, notes, and snippets.

@Rankarusu
Created December 4, 2025 17:21
Show Gist options
  • Select an option

  • Save Rankarusu/013d4f75a2c1fafe3ad0d5d9dad2d611 to your computer and use it in GitHub Desktop.

Select an option

Save Rankarusu/013d4f75a2c1fafe3ad0d5d9dad2d611 to your computer and use it in GitHub Desktop.
Check all surrounding fields in a 2d array, ignoring out of bounds elements
private function checkPosition(int $x, int $y, array $grid): bool
{
$neighbors = [];
$offsets = [
[-1, -1],
[-1, 0],
[-1, 1],
[0, -1],
[0, 1],
[1, -1],
[1, 0],
[1, 1],
];
$maxX = count($grid) - 1;
$maxY = count($grid[0]) - 1;
foreach ($offsets as [$dx, $dy]) {
$nx = $x + $dx;
$ny = $y + $dy;
if ($nx < 0 || $ny < 0 || $nx > $maxX || $ny > $maxY) {
continue;
}
$value = $grid[$nx][$ny];
$neighbors[] = [
$nx,
$ny,
];
}
return $neighbors
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment