PHPackages                             hi-folks/array - 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. hi-folks/array

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

hi-folks/array
==============

Arr class for managing arrays, and Table class for managing bi-dimensional arrays, built on top of the PHP array functions.

v2.0.0(3mo ago)171019[1 issues](https://github.com/Hi-Folks/array/issues)[1 PRs](https://github.com/Hi-Folks/array/pulls)MITPHPPHP ^8.2|^8.3|^8.4|^8.5CI passing

Since Dec 14Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Hi-Folks/array)[ Packagist](https://packagist.org/packages/hi-folks/array)[ Docs](https://github.com/hi-folks/array)[ GitHub Sponsors](https://github.com/Hi-Folks)[ RSS](/packages/hi-folks-array/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (23)Used By (0)

Package array
=============

[](#package-array)

[![PHP Array package](https://raw.githubusercontent.com/Hi-Folks/array/main/cover-arr.png)](https://raw.githubusercontent.com/Hi-Folks/array/main/cover-arr.png)

[![Latest Version on Packagist](https://camo.githubusercontent.com/16e4175a6cd550c8ecdc4fb2a5fb8b1d2edff695327a52d2e948be922e1d3183/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68692d666f6c6b732f61727261792e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/hi-folks/array)[![PHP Unit Tests](https://camo.githubusercontent.com/f68d2af1b3d094d3ca358f274846e9f1021037b3e311d7a0534ee6069ba94f9e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f68692d666f6c6b732f61727261792f72756e2d74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666f722d7468652d6261646765)](https://github.com/Hi-Folks/array/actions)[![Total Downloads](https://camo.githubusercontent.com/7489c18377e17b7b4ba7e0eadc2b181539c1a60a939f501ab8cb1476aad018c2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f68692d666f6c6b732f61727261792e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/hi-folks/array)

This package provides 2 classes:

- **[Arr](#arr-class)** class is built on top of the PHP array functions.
- **[Table](#table-class)** class allow you to manage bidimensional associative array (like a table or tuple).

Arr class
---------

[](#arr-class)

**Arr** exposes methods to create, manage, access the data structure of the array.

The interface (method names, method arguments) are pretty similar to the Javascript Array class.

I built this class because comparing method functions arrays of Javascript and PHP i think (my personal thought) that the JS one is smoother and has a good developer experience (but, again, it's a personal opinion).

The Arr class provides some methods:

- make() create array;
- fromFunction(): create Arr from a function;
- fromValue(): create Arr from a value;
- length(): length/size of the array;
- arr(): returns data with the type PHP array
- get(): get the element by index
- getArr(): get the element (as Arr::class instance) by index (helpful for nested arrays)
- Iterator methods: current(), next(), prev(), key(), valid(), rewind()
- forEach(): execute a function for each element;
- push(): add new element (at the end);
- pop(): remove an element (at the end);
- unshift(): add new element at the start;
- shift(): remove an element from the start;
- append(): append arrays to the current one;
- concat(): return new array joining more arrays, Arr objects or scalar variables;
- join(): joins all elements into a string;
- slice(): returns a sub array;
- indexOf(): find the first occurrence;
- lastIndexOf(): find the last occurrence;
- every(): all elements match a fn();
- some(): at least one element matches a fn();
- filter(): filter elements by a fn();
- map(): apply a fn() for each element;
- flat(): flat an array of arrays;
- flatMap(): map() and flat();
- fill(): fill an array (or a piece of an array);
- reduce(): calculate a fn() with the array as input;
- reduceRight(): like reduce(), but parsing the array in reverse order;
- reverse(): reverse the array;
- sort(): sort the array;
- splice(): changes content of arr removing, replacing and adding elements;
- toString(): the string representing the array (same as join(','));
- isArray(): check if the input is an array;
- from(): for creating new Arr from a string or array-like object;
- findIndex(): for finding the index of some element;
- find(): returns the first element in the array that satisfies the testing function;
- entries(): returns a new Arr object that contains the key/value pairs for each index in the array;
- copyWithin(): copies part of the array to a location but keeps the original length.
- isEmpty(): checks if provided array is empty or not;
- values(): it creates a new Arr object with the values of the current one (keys are skipped)
- set(): ability to set an element to the array with a specific key
- unset(): ability to unset an element by the key

### The `get()` method

[](#the-get-method)

The `get()` method supports keys/indexes with the dot (or custom) notation for retrieving values from nested arrays. For example:

```
$fruits = Arr::make([
    'green' => [
        'kiwi' => '🥝',
        'mango' => '🥭'
    ],
    'red' => [
        'strawberry' => '🍓',
        'apple' => '🍎'
    ],
    'yellow' => [
        'lemon' => '🍋',
        'banana' => '🍌',
    ]
]);
$fruits->get('red'); // 🍓,🍎
$fruits->get('red.strawberry'); // 🍓
```

You can customize the notation with a different character:

```
$fruits->get('red#strawberry', charNestedKey: '#'); // 🍓
```

You can define a default value in the case the key doesn't exist:

```
$fruits->get('red#somestrangefruit',
'🫠', '#'); // 🫠
```

### The `getArr()` method

[](#the-getarr-method)

If you need to manage a complex array (nested array), or an array obtained from a complex JSON structure, you can access a portion of the array and obtain an Arr object. Just because in the case of a complex array the `get()` method could return a classic array.

Let's see an example:

```
    $arr = Arr::make(
        [
            "avocado" =>
                [
                    'name' => 'Avocado',
                    'fruit' => '🥑',
                    'wikipedia' => 'https://en.wikipedia.org/wiki/Avocado'
                ],
            "apple" =>
                [
                    'name' => 'Apple',
                    'fruit' => '🍎',
                    'wikipedia' => 'https://en.wikipedia.org/wiki/Apple'
                ],
            "banana" =>
                [
                    'name' => 'Banana',
                    'fruit' => '🍌',
                    'wikipedia' => 'https://en.wikipedia.org/wiki/Banana'
                ],
            "cherry" =>
                [
                    'name' => 'Cherry',
                    'fruit' => '🍒',
                    'wikipedia' => 'https://en.wikipedia.org/wiki/Cherry'
                ],
        ]
    );
$appleArr = $arr->getArr("apple")
// $appleArr is an Arr instance so that you can access
// to the Arr methods like count()
$arr->getArr("apple")->count();
```

### The `set()` method

[](#the-set-method)

The `set()` method supports keys with the dot (or custom) notation for setting values for nested arrays. If a key doesn't exist, the `set()` method will create a new key and will set the value. If a key already exists, the `set()` method will replace the value related to the key.

For example:

```
$articleText = "Some words as a sample sentence";
$textField = Arr::make();
$textField->set("type", "doc");
$textField->set("content.0.content.0.text", $articleText);
$textField->set("content.0.content.0.type", "text");
$textField->set("content.0.type", "paragraph");
```

So when you try to set a nested key as "content.0.content.0.text", it will be created elements as a nested array. So if you try to dump the value of the array of `$textField` you will see the following structure:

```
var_dump($textField->arr());

array(2) {
  ["type"]=>
  string(3) "doc"
  ["content"]=>
  array(1) {
    [0]=>
    array(2) {
      ["content"]=>
      array(1) {
        [0]=>
        array(2) {
          ["text"]=>
          string(31) "Some words as a sample sentence"
          ["type"]=>
          string(4) "text"
        }
      }
      ["type"]=>
      string(9) "paragraph"
    }
  }
}

```

Table class
-----------

[](#table-class)

Table class allows you to manage bi-dimensional array, something like:

```
[
    ['product' => 'Desk', 'price' => 200, 'active' => true],
    ['product' => 'Chair', 'price' => 100, 'active' => true],
    ['product' => 'Door', 'price' => 300, 'active' => false],
    ['product' => 'Bookcase', 'price' => 150, 'active' => true],
    ['product' => 'Door', 'price' => 100, 'active' => true],
]

```

Each row within the Table will be of type `Arr` so it allows you to lean on all the methods that are available via the `Arr` object.

**Table class** allows you to filter, order, select some fields, create calculated fields. The methods:

- select(): select some fields
- except(): exclude some fields
- where(): filter data
- groupBy(): grouping data into a Table of Tables, with an optional key mode (`GroupByKeyMode::VarExport`, `GroupByKeyMode::Strval`, `GroupByKeyMode::Int`)
- transform(): transforms a specific field with the provided function
- orderBy(): sorting data (ascending or descending)
- toArray(): transform Table object into a native PHP array
- toJson(): convert Table object into a JSON string

`Table` now implements `\Countable` and `\Iterator`, this allows you to count the number of rows and also loop over the rows using common loops.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require hi-folks/array
```

Usage
-----

[](#usage)

To see some examples, I suggest you to take a look to *examples/cheatsheet.php* file,where you can see a lot of example and use cases.

To start quickly

```
// Load the vendor/autoload file
require("./vendor/autoload.php");
// import the Arr class:
use HiFolks\DataType\Arr;
// use static make method to create Arr object
$arr = Arr::make();
$arr->push('Hi');
$arr->push('Folks');
echo $arr->length();
// to access to the "native" PHP array:
print_r($arr->arr());
```

To create an array with random values:

```
require("./vendor/autoload.php");
use HiFolks\DataType\Arr;
$arr = Arr::fromFunction(fn () => random_int(0, 100), 500);
```

You can access to the elements like a native array, but you have also Arr methods:

```
require("./vendor/autoload.php");
use HiFolks\DataType\Arr;
$arr = Arr::make();
$arr[] = "First element";
$arr[] = "Second element";
$count = $arr->length();
// output: 2
$arr->reverse();
echo $arr[0];
// output: Second element
```

Usage of Table class
--------------------

[](#usage-of-table-class)

Starting from:

```
[
    ['product' => 'Desk', 'price' => 200, 'active' => true],
    ['product' => 'Chair', 'price' => 100, 'active' => true],
    ['product' => 'Door', 'price' => 300, 'active' => false],
    ['product' => 'Bookcase', 'price' => 150, 'active' => true],
    ['product' => 'Door', 'price' => 100, 'active' => true],
]

```

I would like to **filter** the rows with price greater than 100, **select** only "product" and "price" fields, and for each rows **create a new field** named "new\_filed" that is a calculated field (doubling the price):

```
use HiFolks\DataType\Table;
$dataTable = [
    ['product' => 'Desk', 'price' => 200, 'active' => true],
    ['product' => 'Chair', 'price' => 100, 'active' => true],
    ['product' => 'Door', 'price' => 300, 'active' => false],
    ['product' => 'Bookcase', 'price' => 150, 'active' => true],
    ['product' => 'Door', 'price' => 100, 'active' => true],
];
$table = Table::make($dataTable);
$arr = $table
    ->select('product' , 'price')
    ->where('price', ">", 100)
    ->calc('new_field', fn ($item) => $item['price'] * 2);
```

The result is

```
HiFolks\DataType\Table::__set_state(array(
   'rows' =>
  array (
    0 =>
    HiFolks\DataType\Arr::__set_state(array(
       'arr' =>
      array (
        'product' => 'Desk',
        'price' => 200,
        'new_field' => 400,
      ),
    )),
    1 =>
    HiFolks\DataType\Arr::__set_state(array(
       'arr' =>
      array (
        'product' => 'Door',
        'price' => 300,
        'new_field' => 600,
      ),
    )),
    2 =>
    HiFolks\DataType\Arr::__set_state(array(
       'arr' =>
      array (
        'product' => 'Bookcase',
        'price' => 150,
        'new_field' => 300,
      ),
    )),
  ),
))

```

### Grouping data with `groupBy()`

[](#grouping-data-with-groupby)

The `groupBy()` method groups rows by a field value and returns a **Table of Tables**. You can then use `get()` to access each group by its key and drill into the rows:

```
use HiFolks\DataType\Table;

$table = Table::make([
    ['product' => 'Desk', 'price' => 200, 'active' => true],
    ['product' => 'Chair', 'price' => 100, 'active' => true],
    ['product' => 'Door', 'price' => 300, 'active' => false],
    ['product' => 'Bookcase', 'price' => 150, 'active' => true],
    ['product' => 'Door', 'price' => 100, 'active' => true],
]);

$grouped = $table->groupBy('product');
$grouped->count(); // 4 groups: Desk, Chair, Door, Bookcase

$deskItems = $grouped->get('Desk');
$deskItems->count(); // 1

$doorItems = $grouped->get('Door');
$doorItems->count(); // 2

$firstDoor = $doorItems->first();
$firstDoor->get('price');   // 300
$firstDoor->get('product'); // 'Door'
$firstDoor->get('active');  // false
```

Because `groupBy()` returns a Table, you can chain it with `where()` and `orderBy()` to build powerful queries. For example, to get the cheapest active product in each group:

```
$cheapest = $table
    ->where('active', '=', true)
    ->orderBy('price', 'asc')
    ->groupBy('product');

$cheapest->get('Door')->first()->get('price'); // 100
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Roberto B.](https://github.com/roberto-butti)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

53

—

FairBetter than 97% of packages

Maintenance85

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 53.2% 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

Every ~101 days

Recently: every ~156 days

Total

16

Last Release

98d ago

Major Versions

0.1.1 → v1.0.12024-05-23

v1.1.0 → v2.0.02026-02-08

PHP version history (3 changes)0.0.2PHP ^8.0

v1.0.1PHP ^8.1|^8.2|^8.3

v2.0.0PHP ^8.2|^8.3|^8.4|^8.5

### Community

Maintainers

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

---

Top Contributors

[![roberto-butti](https://avatars.githubusercontent.com/u/678434?v=4)](https://github.com/roberto-butti "roberto-butti (202 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (122 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (27 commits)")[![RoadSigns](https://avatars.githubusercontent.com/u/5822139?v=4)](https://github.com/RoadSigns "RoadSigns (17 commits)")[![Tautvydaskarvelis](https://avatars.githubusercontent.com/u/143169563?v=4)](https://github.com/Tautvydaskarvelis "Tautvydaskarvelis (5 commits)")[![LeoVie](https://avatars.githubusercontent.com/u/7249788?v=4)](https://github.com/LeoVie "LeoVie (2 commits)")[![tharun634](https://avatars.githubusercontent.com/u/53267275?v=4)](https://github.com/tharun634 "tharun634 (2 commits)")[![nuernbergerA](https://avatars.githubusercontent.com/u/13331388?v=4)](https://github.com/nuernbergerA "nuernbergerA (1 commits)")[![martijnengler](https://avatars.githubusercontent.com/u/929994?v=4)](https://github.com/martijnengler "martijnengler (1 commits)")[![AsherMoshav](https://avatars.githubusercontent.com/u/1633267?v=4)](https://github.com/AsherMoshav "AsherMoshav (1 commits)")

---

Tags

arrayhacktoberfestphparrayhi-folks

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/hi-folks-array/health.svg)

```
[![Health](https://phpackages.com/badges/hi-folks-array/health.svg)](https://phpackages.com/packages/hi-folks-array)
```

###  Alternatives

[doctrine/collections

PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.

6.0k411.1M1.2k](/packages/doctrine-collections)[symfony/property-access

Provides functions to read and write from/to an object or array using a simple string notation

2.8k295.3M2.5k](/packages/symfony-property-access)[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.1k394.3M1.5k](/packages/nette-utils)[league/config

Define configuration arrays with strict schemas and access values with dot notation

564302.2M24](/packages/league-config)[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k9.2M108](/packages/cuyz-valinor)[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.2k412.9k11](/packages/aimeos-map)

PHPackages © 2026

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