PHPackages                             jmasci/matrix-builder - 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. jmasci/matrix-builder

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

jmasci/matrix-builder
=====================

A mutable matrix object with methods for sorting rows/columns, adding/removing cells, and a few other things.

012[1 PRs](https://github.com/j-masci/php-matrix-builder/pulls)PHPCI passing

Since Jan 23Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/j-masci/php-matrix-builder)[ Packagist](https://packagist.org/packages/jmasci/matrix-builder)[ RSS](/packages/jmasci-matrix-builder/feed)WikiDiscussions master Synced 6d ago

READMEChangelogDependenciesVersions (3)Used By (0)

A matrix in this context is an indexed array of indexed arrays. This library is a single class that lets you incrementally build such a matrix, and then offers some useful row and column methods such as simple getters/setters, deletion of entire rows or columns, and sorting of rows or columns.

Is a class/encapsulation the best way to do this? Not sure.

Couldn't we just use primitive data structures and write pure functions? Probably. One of the reasons I used a class was that column operations have to be performed differently than row operations and are generally harder. So it seemed convenient to just write one row and one column method for each operation.

One thing I could have done was write a function to convert rows into columns (and column into rows). Then any function you write to operate on rows could be achieved on columns by calling the "inversion" function before and after the row operation (hope that makes sense). Anyways, for this library, all the functionality is wrapped up in a class which mostly encapsulates its data but does not prevent you from manipulating the internal data structure if you need to.

### Basic Usage

[](#basic-usage)

In general, every row method has a corresponding column method.

```
use JMasci\MatrixBuilder;

// create a new empty matrix
$matrix = new MatrixBuilder();

// sets some values.
$matrix->set( 'row_1', 'col_1', 'value 1,1' );
$matrix->set( 'row_1', 'col_2', 'value 1,2' );
$matrix->set( 'row_2', 'col_1', 'value 2,1' );
$matrix->set( 'row_2', 'col_2', 'value 2,2' );

// returns "value 1,2"
$matrix->get( 'row_1', 'col_2' );

// returns [ 'row_1' => 'value 1,1', 'row_2' => 'value 2,1' ]
$matrix->get_column( 'col_1' );

// returns [ 'col_1' => 'value 1,1', 'col_2' => 'value 1,2' ]
$matrix->get_row( 'row_1' );

print_r( $matrix->get_matrix() );
```

```
gives you:

Array
(
    [row_1] => Array
        (
            [col_1] => value 1,1
            [col_2] => value 1,2
        )

    [row_2] => Array
        (
            [col_1] => value 2,1
            [col_2] => value 2,2
        )

)

```

### Sorting, deleting, and settings totals

[](#sorting-deleting-and-settings-totals)

```
// puts the given rows first. If you pass in a row that doesn't exist it will ignore it.
$matrix->apply_row_sort( [ 'row_2', 'row_1' ]);

// alternate sort method accepting an anonymous function. This would sort columns alphabetically.
$matrix->sort_rows( function( $keys ) {
    asort( $keys );
    return $keys;
});

// the set function also accepts an anonymous function, which will be provided the previous value.
// the value afterwards will be 100.
$matrix->set( 'row_1', 'col_1', 95 );
$matrix->set( 'row_1', 'col_1', $matrix::get_incrementer( 5 ) );

$matrix->delete_row( 'row_2' );

// adds a new column to each row whose value is determined by the callback function.
// useful when your values are numeric.
$matrix->set_row_totals( function( $row, $key ) { return array_sum( $row ); }, 'total' );
```

#### Real World Example

[](#real-world-example)

You could do some similar things in SQL using group by and count. But there's more flexibility when constructing the matrix in PHP.

```
use JMasci\MatrixBuilder;

$matrix = new MatrixBuilder();

foreach ( query_posts_and_join_authors() as $post ) {
    // each time we call set we either add 1 to the previous value
    // or initialize a new row and/or column and then add 1.
    $matrix->set( $post->author_name, date( 'm Y', strtotime( $post->post_date ) ), $matrix::get_incrementer(1));
}

// assume the query already sorted by date. Rows will remain sorted in the order that they were added.

// sort authors by name
$matrix->sort_columns( function( $keys ){
    sort( $keys );
    return $keys;
});

$matrix->set_row_totals( $matrix::get_array_summer(), '__Total' );
$matrix->set_column_totals( $matrix::get_array_summer(), '__Total' );

$data = $matrix->convert_to_record_set_with_headings( "Authors vs. Post Dates");
```

Useful for rendering a table such as...

Authors vs. Post DatesAuthor 1Author 2Author 3\_\_TotalOctober 20193429November 2019122519December 20195308January 20202271544February 20200000\_\_Total42162280Possible Future Addition: Allow cells to use formula's. This can get complicated though.

###  Health Score

27

↑

LowBetter than 49% of packages

Maintenance61

Regular maintenance activity

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/c60f943028a4f2dd0b44e1adea05c55bf2b82ca455eabb2a73493f76700190fd?d=identicon)[joel-masci](/maintainers/joel-masci)

---

Top Contributors

[![j-masci](https://avatars.githubusercontent.com/u/24510397?v=4)](https://github.com/j-masci "j-masci (10 commits)")

### Embed Badge

![Health badge](/badges/jmasci-matrix-builder/health.svg)

```
[![Health](https://phpackages.com/badges/jmasci-matrix-builder/health.svg)](https://phpackages.com/packages/jmasci-matrix-builder)
```

###  Alternatives

[volcengine/volc-sdk-php

Volcengine SDK for PHP

35113.0k4](/packages/volcengine-volc-sdk-php)[nabilhassen/laravel-usage-limiter

A laravel package to manage and limit usages/seats by plan, users, or other models

1803.2k](/packages/nabilhassen-laravel-usage-limiter)[workbunny/webman-nacos

Webman plugin workbunny/webman-nacos

673.9k](/packages/workbunny-webman-nacos)[zgldh/crc16-php

crc16 hash methods for PHP

1639.6k1](/packages/zgldh-crc16-php)

PHPackages © 2026

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