Created
December 4, 2025 17:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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