php 54 lines · 7 steps

A flat-array bitmap grid in PHP

A 2D byte grid backed by a single SplFixedArray, mapping (x, y) coordinates onto a flat index.

Explained by highlit
1final class BitmapGrid
2{
3 private SplFixedArray $cells;
4 
5 public function __construct(
6 private readonly int $width,
7 private readonly int $height,
8 ) {
9 $this->cells = new SplFixedArray($width * $height);
10 
11 for ($i = 0, $n = $this->cells->getSize(); $i < $n; $i++) {
12 $this->cells[$i] = 0;
13 }
14 }
15 
16 public function set(int $x, int $y, int $value): void
17 {
18 $this->cells[$this->offset($x, $y)] = $value & 0xFF;
19 }
20 
21 public function get(int $x, int $y): int
22 {
23 return $this->cells[$this->offset($x, $y)];
24 }
25 
26 public function fillRegion(int $x0, int $y0, int $x1, int $y1, int $value): void
27 {
28 for ($y = $y0; $y <= $y1; $y++) {
29 $base = $y * $this->width;
30 for ($x = $x0; $x <= $x1; $x++) {
31 $this->cells[$base + $x] = $value & 0xFF;
32 }
33 }
34 }
35 
36 public function histogram(): array
37 {
38 $counts = array_fill(0, 256, 0);
39 foreach ($this->cells as $value) {
40 $counts[$value]++;
41 }
42 
43 return $counts;
44 }
45 
46 private function offset(int $x, int $y): int
47 {
48 if ($x < 0 || $x >= $this->width || $y < 0 || $y >= $this->height) {
49 throw new OutOfRangeException("($x, $y) is outside the grid");
50 }
51 
52 return $y * $this->width + $x;
53 }
54}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing a 2D grid as a flat row-major array trades coordinate math for compact, cache-friendly memory.
  2. 2SplFixedArray gives fixed-size, integer-indexed storage that's leaner than a dynamic PHP array.
  3. 3Centralizing index translation in one helper keeps bounds-checking and layout logic in a single place.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A flat-array bitmap grid in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code