PHPackages                             reallifekip/grid-map - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. reallifekip/grid-map

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

reallifekip/grid-map
====================

A lightweight grid-based area mapping library for defining rectangular regions in a cell grid.

v1.0.0(8mo ago)010MITPHPPHP ^8.0

Since Sep 4Pushed 6mo agoCompare

[ Source](https://github.com/ReallifeKip/GridMap)[ Packagist](https://packagist.org/packages/reallifekip/grid-map)[ RSS](/packages/reallifekip-grid-map/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)DependenciesVersions (2)Used By (0)

GridMap
=======

[](#gridmap)

**Language:** English | [繁體中文](README.zh-TW.md)

A lightweight, zero-dependency PHP micro-library for **grid slicing**. It divides a fixed-size plane (e.g., 1920x1080 canvas, video wall, media composition, dashboard, or layout system) into a grid according to specified proportions, then sequentially “fills” rectangular slices into available cells and returns their pixel coordinates and sizes.

`GridMap` uses a simple row-major first-fit scanning algorithm to find the first available area that can fit a slice of the requested grid width/height. If successful, the area is marked as occupied and the next slice is processed. If a slice cannot fit, an exception is thrown.

---

✨ Features Overview
-------------------

[](#-features-overview)

- ✅ Single class, easy to understand and integrate
- ✅ No extensions required: pure PHP ≥ 8.0
- ✅ Define slices in “grid units” and automatically convert to pixel coordinates `x,y,width,height`
- ✅ Deterministic first-fit placement, reproducible results
- ✅ Uses integer division `intdiv` to avoid floating-point rounding errors
- ✅ Automatically detects unplaceable slices and throws clear exceptions
- ✅ Suitable for dynamic layouts, video walls, auto-layout suggestions
- ⚠️ If not fully filled, triggers an `E_USER_NOTICE` about remaining empty cells

---

📦 Installation
--------------

[](#-installation)

```
composer require reallifekip/grid-map
```

---

🚀 Quick Start
-------------

[](#-quick-start)

```
use ReallifeKip\GridMap\GridMap;

// Canvas size: 1920x1080; divided into 24 x 12 grid (typical 16:9 split)
$gm = new GridMap(
	area_w: 1920,
	area_h: 1080,
	grids_w: 24,
	grids_h: 12,
);

// Define slices: each element is [grid_width, grid_height]
// Example: [6,6] means 6x6 grid cells
$slices = [
	[6, 6],
	[6, 6],
	[6, 6],
	[6, 6],
	[12, 6], // width 12, height 6
	[12, 6],
];

$areas = $gm->slice($slices);

print_r($areas);
```

Example output (actual may vary depending on allocation):

```
Array
(
	[0] => Array ( [x] => 0    [y] => 0    [width] => 480  [height] => 540 )
	[1] => Array ( [x] => 480  [y] => 0    [width] => 480  [height] => 540 )
	[2] => Array ( [x] => 960  [y] => 0    [width] => 480  [height] => 540 )
	[3] => Array ( [x] => 1440 [y] => 0    [width] => 480  [height] => 540 )
	[4] => Array ( [x] => 0    [y] => 540  [width] => 960  [height] => 540 )
	[5] => Array ( [x] => 960  [y] => 540 [width] => 960  [height] => 540 )
)
```

> The above width/height are actual pixels, calculated by dividing `(total_canvas / grid_count)`. For example: `1920/24=80`, `1080/12=90`. A 6-grid width = 6 × 80 = 480 pixels; a 6-grid height = 6 × 90 = 540 pixels.

---

🧠 Core Concept
--------------

[](#-core-concept)

TermDescription`area_w`, `area_h`Total canvas size (pixels)`grids_w`, `grids_h`Number of grid divisions (horizontal / vertical)slice `[cw, ch]`Slice rectangle defined in grid units, not pixelsreturn `areas[]`Each placed slice, with `x`,`y`,`width`,`height` (px)Steps (simplified):

1. Compute all grid line coordinates: `cols[x] = intdiv(x * area_w, grids_w)`, `rows[y] = intdiv(y * area_h, grids_h)`
2. Use a 1D array to mark whether each cell is occupied
3. For each slice:

    - Scan row-major for the first fitting location
    - Check if all covered cells are free
    - Mark occupied and convert to pixel rectangle
4. Throw exception if slice cannot be placed
5. If leftover space exists, trigger an `E_USER_NOTICE` (informational, can be ignored or handled)

---

✅ Example Use Cases
-------------------

[](#-example-use-cases)

Use CaseDescriptionMedia/Video wallAutomatically arrange multiple video sourcesVideo compositingMap multiple tracks into fixed canvas coordinatesRealtime dashboardAuto-generate initial layouts for widget cardsGame/Level editorPlan map or scene block placementsAd screen layoutPlace multiple ad creatives into grid layout---

🛠️ Advanced Example: Mixed Sizes &amp; Error Handling
-----------------------------------------------------

[](#️-advanced-example-mixed-sizes--error-handling)

```
use ReallifeKip\GridMap\GridMap;

$gm = new GridMap(1200, 800, 20, 10);

$slices = [
	[4, 4], // A
	[8, 4], // B
	[4, 2], // C
	[6, 6], // D may not fit later
];

try {
	$areas = $gm->slice($slices);
} catch (\Exception $e) {
	// Thrown if a slice cannot be placed
	echo 'Slice placement failed: ' . $e->getMessage();
}
```

---

⚠️ Notes
--------

[](#️-notes)

1. Each slice must be `[cw, ch]` of two positive integers
2. `cw` cannot exceed `grids_w`, `ch` cannot exceed `grids_h`
3. Strategy is “first feasible placement”: not optimized for space, just deterministic
4. For “optimal packing / rotation / reordering”, preprocess slices (e.g., sort by size)
5. Returned array indexes correspond 1-to-1 with input slice order
6. To ignore the unfilled notice, define a custom error handler or suppress `E_USER_NOTICE`

---

🔍 Return Data Format
--------------------

[](#-return-data-format)

```
[
	[ 'x' => int, 'y' => int, 'width' => int, 'height' => int ],
	...
]
```

---

🧪 Testing Suggestions (example)
-------------------------------

[](#-testing-suggestions-example)

You may write PHPUnit tests to verify:

- Slice count matches returned array count
- No overlapping rectangles (check original cell intersections)
- When all slices fit, occupied grid count = `grids_w * grids_h`
- Oversized slices trigger `Exception`

---

📄 License
---------

[](#-license)

This package uses the [MIT License](./LICENSE) – Free for commercial use / modification / distribution, just keep copyright notice.

---

👤 Developer Info
----------------

[](#-developer-info)

Author: Kip () GitHub: [@ReallifeKip](https://github.com/ReallifeKip)

If this project helps you: feel free to Star, share, or suggest improvements!

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance63

Regular maintenance activity

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

250d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cf19a85c0944db75a08b13fc1914dafb1b9a38ac9369922425258f8f994cc479?d=identicon)[ReallifeKip](/maintainers/ReallifeKip)

---

Top Contributors

[![ReallifeKip](https://avatars.githubusercontent.com/u/91828793?v=4)](https://github.com/ReallifeKip "ReallifeKip (4 commits)")

---

Tags

gridgridmapgrid-map

### Embed Badge

![Health badge](/badges/reallifekip-grid-map/health.svg)

```
[![Health](https://phpackages.com/badges/reallifekip-grid-map/health.svg)](https://phpackages.com/packages/reallifekip-grid-map)
```

###  Alternatives

[desandro/masonry

Cascading grid layout library

16.7k424.4k1](/packages/desandro-masonry)[kartik-v/yii2-grid

Yii 2 GridView on steroids. Various enhancements and utilities for the Yii 2.0 GridView widget.

5576.6M179](/packages/kartik-v-yii2-grid)[himiklab/yii2-sortable-grid-view-widget

Sortable modification of standard Yii2 GridView widget

80351.1k7](/packages/himiklab-yii2-sortable-grid-view-widget)[codenco-dev/nova-grid-system

A Laravel Nova tool to have a grid system

80300.1k](/packages/codenco-dev-nova-grid-system)[kotchuprik/yii2-sortable-widgets

Implementation Rubaxa/Sortable for Yii2. Sortable grid view inside.

61132.2k6](/packages/kotchuprik-yii2-sortable-widgets)[leantony/laravel-grid

A grid view for laravel, inspired by the yii2 grid widget

9060.2k](/packages/leantony-laravel-grid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
