PHPackages                             nawebco/box-packer - 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. nawebco/box-packer

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

nawebco/box-packer
==================

Yet another solution to the packing/knapsack problem.

2.2.1(6y ago)22.7k↓50%11MITPHPPHP &gt;=7.2

Since May 9Pushed 6y ago2 watchersCompare

[ Source](https://github.com/north-american-web/box-packer)[ Packagist](https://packagist.org/packages/nawebco/box-packer)[ RSS](/packages/nawebco-box-packer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (13)Used By (1)

Yet Another Box Packer Package
==============================

[](#yet-another-box-packer-package)

This module implements a rough solution to the [bin packing problem](https://en.wikipedia.org/wiki/Bin_packing_problem). It was originally developed to support an e-commerce merchant's desire to offer a shipping option only if all the items in an order would fit into a certain box. This implementation supports multiple boxes as well.

The bin-packing problem is [NP hard](https://en.wikipedia.org/wiki/NP-hardness). This implementation is a heuristic that won't always provide an optimal solution, but it is fast and it's unlikely to provide a solution that's too difficult for a human to replicate when packing a box with real (physical) items.

Briefly, this algorithm works as follows:

- Largest (by volume) items are packed first.
- Items are packed in layers. Layers are as wide and long as the box and are as tall as the tallest object in the layer.
- Items are packed alongside each other in each layer with the longest edge on the bottom, oriented in a way that yields the largest remaining area.
- If an item doesn't fit in any existing layers, the algorithm starts a new layer.
- Each time an item is added, the algorithm attempts to add it to the lower layers in any remaining spaces (including above other items), unless doing so would increase the height of the layer.
- Each time a new layer is started, the algorithm checks to make sure the total height of the layers hasn't exceeded the box height.

Using NAWebCo\\BoxPacker
------------------------

[](#using-nawebcoboxpacker)

To install, run `composer require nawebco/box-packer` in your project's root directory. If you aren't already using Composer's autoloader, be sure to require `vendor/autoload.php` wherever you need access to the BoxPacker.

Usage example:

```
