PHPackages                             voku/arrayy - 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. voku/arrayy

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

voku/arrayy
===========

Array manipulation library for PHP, called Arrayy!

7.9.6(3y ago)4875.5M—5.7%34[4 issues](https://github.com/voku/Arrayy/issues)[10 PRs](https://github.com/voku/Arrayy/pulls)15MITPHPPHP &gt;=7.0.0

Since Jul 29Pushed 1mo ago14 watchersCompare

[ Source](https://github.com/voku/Arrayy)[ Packagist](https://packagist.org/packages/voku/arrayy)[ Fund](https://www.paypal.me/moelleken)[ GitHub Sponsors](https://github.com/voku)[ RSS](/packages/voku-arrayy/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (180)Used By (15)

[![SWUbanner](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://github.com/vshymanskyy/StandWithUkraine/blob/main/docs/README.md)

[![Build Status](https://github.com/voku/Arrayy/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/voku/Arrayy/actions)[![codecov.io](https://camo.githubusercontent.com/ab617ee4985eafac20d7be1b5ea30603c348425ee26cef0b2e290297d9b0be69/68747470733a2f2f636f6465636f762e696f2f6769746875622f766f6b752f4172726179792f636f7665726167652e7376673f6272616e63683d6d6173746572)](https://codecov.io/github/voku/Arrayy?branch=master)[![Codacy Badge](https://camo.githubusercontent.com/882f771442af0d3e9a433ff3224ef29d82d725e8154d1fafa875d29275a1b626/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f67726164652f6238633463383861303633353435643738376532613466316635646664663233)](https://www.codacy.com/app/voku/Arrayy)[![Latest Stable Version](https://camo.githubusercontent.com/852cf36f6238c7826cffdaf42e34b663fbd32670244711ed8a92146480d38483/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f6172726179792f762f737461626c65)](https://packagist.org/packages/voku/arrayy)[![Total Downloads](https://camo.githubusercontent.com/46d37ea0c37ee6b43678aebea34170d083f4d14c87971ccdeca15ffbac4f962d/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f6172726179792f646f776e6c6f616473)](https://packagist.org/packages/voku/arrayy)[![License](https://camo.githubusercontent.com/80150af186768652215c68d4d556e93816e9f575862abfe8fb9432f6c2bf8108/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f6172726179792f6c6963656e7365)](https://packagist.org/packages/voku/arrayy)[![Donate to this project using Paypal](https://camo.githubusercontent.com/0d6e4d8b50b5983a58205941b1a581b1305903393b7a39da574e3f60af3c7f5b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617970616c2d646f6e6174652d79656c6c6f772e737667)](https://www.paypal.me/moelleken)[![Donate to this project using Patreon](https://camo.githubusercontent.com/f9e075baad95563481d35174d43ef50757281abb6bc795d0f473fad452afa030/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617472656f6e2d646f6e6174652d79656c6c6f772e737667)](https://www.patreon.com/voku)

🗃 Arrayy
========

[](#-arrayy)

A PHP array manipulation library. Compatible with PHP 7+ &amp; PHP 8+

```
\Arrayy\Type\StringCollection::create(['Array', 'Array'])->unique()->append('y')->implode() // Arrayy
```

[![Ed8ypbzWAAIinwv-1](https://user-images.githubusercontent.com/264695/183588620-3f1c2c32-e4aa-4069-9d12-23265689ba0b.jpeg)](https://user-images.githubusercontent.com/264695/183588620-3f1c2c32-e4aa-4069-9d12-23265689ba0b.jpeg)

- [Installation](#installation-via-composer-require)
- [Multidimensional ArrayAccess](#multidimensional-arrayaccess)
- [PhpDoc @property checking](#phpdoc-property-checking)
- [OO and Chaining](#oo-and-chaining)
- [Collections](#collections)
    - [Pre-Defined Typified Collections](#pre-defined-typified-collections)
    - [Convert JSON-Data into Collections](#convert-json-data-into-objects-collection)
- [Class methods](#class-methods)
    - [use a "default object"](#use-a-default-object)
    - [create](#createarray-array--arrayy-immutable)
    - [createByReference](#createbyreferencearray-array--arrayy-mutable)
    - [createFromJson](#createfromjsonstring-json--arrayy-immutable)
    - [createFromJsonMapper](#createfromjsonmapperstring-json--arrayy-immutable)
    - [createFromObject](#createfromobjectarrayaccess-object--arrayy-immutable)
    - [createFromObjectVars](#createfromobjectvarsobject-object--arrayy-immutable)
    - [createWithRange](#createwithrange--arrayy-immutable)
    - [createFromGeneratorImmutable](#createfromgeneratorimmutable--arrayy-immutable)
    - [createFromGeneratorFunction](#createfromgeneratorfunction--arrayy-immutable)
    - [createFromString](#createfromstringstring-str--arrayy-immutable)
- [Instance methods](#instance-methods)
    - ["set an array value"](#set-an-array-value)
    - ["set an array value via dot-notation"](#setmixed-key-mixed-value--arrayy-immutable)
    - ["get an array value"](#get-an-array-value)
    - ["get an array value via dot-notation"](#getstring-key-null-default-null-array--mixed)
    - ["get the array"](#get-the-array)
    - ["delete an array value"](#delete-an-array-value)
    - ["check if an array value is-set"](#check-if-an-array-value-is-set)
    - ["simple loop with an Arrayy-object"](#simple-loop-with-an-arrayy-object)
    - [overview](#arrayy-methods)
- [Tests](#tests)
- [License](#license)

Installation via "composer require"
-----------------------------------

[](#installation-via-composer-require)

```
composer require voku/arrayy
```

Multidimensional ArrayAccess
----------------------------

[](#multidimensional-arrayaccess)

You can access / change the array via Object, Array or with "Arrayy"-syntax.

### Access via "Arrayy"-syntax: (dot-notation)

[](#access-via-arrayy-syntax-dot-notation)

```
$arrayy = new A(['Lars' => ['lastname' => 'Moelleken']]);

$arrayy->get('Lars'); // ['lastname' => 'Moelleken']
$arrayy->get('Lars.lastname'); // 'Moelleken'
```

### Access via "array"-syntax:

[](#access-via-array-syntax)

```
$arrayy = new A(['Lars' => ['lastname' => 'Moelleken']]);

$arrayy['Lars'];             // ['lastname' => 'Moelleken']
$arrayy['Lars']['lastname']; // 'Moelleken'
```

### Access via "object"-syntax:

[](#access-via-object-syntax)

```
$arrayy = new A(['Lars' => ['lastname' => 'Moelleken']]);

$arrayy->Lars; // Arrayy['lastname' => 'Moelleken']
$arrayy->Lars->lastname; // 'Moelleken'
```

### Set values via "Arrayy"-syntax: (dot-notation)

[](#set-values-via-arrayy-syntax-dot-notation)

```
$arrayy = new A(['Lars' => ['lastname' => 'Mueller']]);

$arrayy->set('Lars.lastname', 'Moelleken');
$arrayy->get('Lars.lastname'); // 'Moelleken'
```

### Set values via "array"-syntax:

[](#set-values-via-array-syntax)

```
$arrayy = new A(['Lars' => ['lastname' => 'Moelleken']]);

$arrayy['Lars'] = array('lastname' => 'Müller');
$arrayy['Lars']['lastname']; // 'Müller'
```

### Set values via "object"-syntax:

[](#set-values-via-object-syntax)

```
$arrayy = new A(['Lars' => ['lastname' => 'Moelleken']]);

$arrayy->Lars = array('lastname' => 'Müller');
$arrayy->Lars->lastname; // 'Müller'
```

PhpDoc @property checking
-------------------------

[](#phpdoc-property-checking)

The library offers a type checking for @property phpdoc-class-comments, as seen below:

```
/**
 * @property int        $id
 * @property int|string $firstName
 * @property string     $lastName
 * @property null|City  $city
 *
 * @extends  \Arrayy\Arrayy
 */
class User extends \Arrayy\Arrayy
{
  protected $checkPropertyTypes = true;

  protected $checkPropertiesMismatchInConstructor = true;
}

/**
 * @property string|null $plz
 * @property string      $name
 * @property string[]    $infos
 *
 * @extends  \Arrayy\Arrayy
 */
class City extends \Arrayy\Arrayy
{
    protected $checkPropertyTypes = true;

    protected $checkPropertiesMismatchInConstructor = true;
}

$cityMeta = City::meta();
$city = new City(
    [
        $cityMeta->plz   => null,
        $cityMeta->name  => 'Düsseldorf',
        $cityMeta->infos => ['lall'],
    ]
);

$userMeta = User::meta();
$user = new User(
    [
        $userMeta->id        => 1,
        $userMeta->firstName => 'Lars',
        $userMeta->lastName  => 'Moelleken',
        $userMeta->city      => $city,
    ]
);

var_dump($user['lastName']); // 'Moelleken'
var_dump($user[$userMeta->lastName]); // 'Moelleken'
var_dump($user->lastName); // Moelleken

var_dump($user['city.name']); // 'Düsseldorf'
var_dump($user[$userMeta->city][$cityMeta->name]); // 'Düsseldorf'
var_dump($user->city->name); // Düsseldorf
```

- "checkPropertyTypes": activate the type checking for all defined @property in the class-phpdoc
- "checkPropertiesMismatchInConstructor": activate the property mismatch check, so you can only add an array with all needed properties (or an empty array) into the constructor

OO and Chaining
---------------

[](#oo-and-chaining)

The library also offers OO method chaining, as seen below:

simple example:

```
echo a(['fòô', 'bàř', 'bàř'])->unique()->reverse()->implode(','); // 'bàř,fòô'
```

complex example:

```
/**
 * @property int    $id
 * @property string $firstName
 * @property string $lastName
 *
 * @extends  \Arrayy\Arrayy
 */
class User extends \Arrayy\Arrayy
{
  protected $checkPropertyTypes = true;

  protected $checkPropertiesMismatchInConstructor = true;
}

/**
 * @template TKey of array-key
 * @extends  AbstractCollection
 */
class UserCollection extends \Arrayy\Collection\AbstractCollection
{
    /**
     * The type (FQCN) associated with this collection.
     *
     * @return string
     */
    public function getType()
    {
        return User::class;
    }
}

$m = User::meta();

$data = static function () use ($m) {
    yield new User([$m->id => 40, $m->firstName => 'Foo', $m->lastName => 'Moelleken']);
    yield new User([$m->id => 30, $m->firstName => 'Sven', $m->lastName => 'Moelleken']);
    yield new User([$m->id => 20, $m->firstName => 'Lars', $m->lastName => 'Moelleken']);
    yield new User([$m->id => 10, $m->firstName => 'Lea', $m->lastName => 'Moelleken']);
};

$users = UserCollection::createFromGeneratorFunction($data);
$names = $users
    ->filter(static function (User $user): bool {
        return $user->id customSortValuesImmutable(static function (User $a, User $b): int {
        return $a->firstName  $b->firstName;
    })
    ->map(static function (User $user): string {
        return $user->firstName;
    })
    ->implode(';');

static::assertSame('Lars;Lea;Sven', $names);
```

Implemented Interfaces
----------------------

[](#implemented-interfaces)

`Arrayy\Arrayy` implements the `IteratorAggregate` interface, meaning that `foreach` can be used with an instance of the class:

```
$arrayy = a(['fòôbàř', 'foo']);
foreach ($arrayy as $value) {
    echo $value;
}
// 'fòôbàř'
// 'foo'
```

It implements the `Countable` interface, enabling the use of `count()` to retrieve the number of elements in the array:

```
$arrayy = a(['fòô', 'foo']);
count($arrayy);  // 2
```

PHP 5.6 Creation
----------------

[](#php-56-creation)

As of PHP 5.6, [`use function`](https://wiki.php.net/rfc/use_function) is available for importing functions. Arrayy exposes a namespaced function, `Arrayy\create`, which emits the same behaviour as `Arrayy\Arrayy::create()`. If running PHP 5.6, or another runtime that supports the `use function` syntax, you can take advantage of an even simpler API as seen below:

```
use function Arrayy\create as a;

// Instead of: A::create(['fòô', 'bàř'])->reverse()->implode();
a(['fòô', 'bàř'])->reverse()->implode(','); // 'bàř,fòô'
```

Collections
-----------

[](#collections)

If you need to group objects together, it's not a good idea to use a simple array or Arrayy object. For these cases you can use the `AbstractCollection`class.

It will throw a `InvalidArgumentException` if you try to add a non valid object into the collection.

e.g.: "YOURCollection.php" (see example `/tests/CollectionTest.php` on github)

```
use Arrayy\Collection\AbstractCollection;

/**
 * @extends  AbstractCollection
 */
class YOURCollection extends AbstractCollection
{
    /**
     * The type (FQCN) associated with this collection.
     *
     * @return string
     */
    public function getType(): string
    {
        return YOURInterface::class;
    }
}

$YOURobject1 = new YOURClass();
$YOURobject2 = new YOURClass();

$YOURcollection = new YOURCollection($YOURobject1);
$YOURcollection->add($YOURobject2); // add one more object

// Or, you can use an array of objects.
//
// $YOURcollection = new YOURCollection([$YOURobject1, $YOURobject2]);

// Or, if you don't want to create new classes ...
// ... and you don't need typehints and autocompletion via classes.
//
// $YOURcollection = \Arrayy\Collection::construct(YOURInterface::class, [$YOURobject1]);
// $YOURcollection->add($YOURobject2); // add one more object

// Or, if you don't like classes at all. ;-)
//
// $YOURcollection = \Arrayy\collection(YOURInterface::class, [$YOURobject1]);
// $YOURcollection->add($YOURobject2); // add one more object

foreach ($YOURcollection as $YOURobject) {
    if ($YOURobject instanceof YOURInterface) {
        // Do something with $YOURobject
    }
}
```

You can also use "dot-notation" to get data from your collections e.g. `$YOURcollection->get('3123.foo.bar');`

Pre-Defined Typified Collections
--------------------------------

[](#pre-defined-typified-collections)

### simple example

[](#simple-example)

This will throw a "TypeError"-Exception.

```
use Arrayy\Type\StringCollection;

$collection = new StringCollection(['A', 'B', 'C', 1]);
```

### complex example

[](#complex-example)

This will NOT throw a "TypeError"-Exception.

```
use Arrayy\Type\IntCollection;
use Arrayy\Type\StringCollection;
use Arrayy\Type\InstancesCollection;
use Arrayy\Type\TypeInterface;

$collection = InstancesCollection::construct(
    TypeInterface::class,
    [new StringCollection(['A', 'B', 'C']), new IntCollection([1])]
);

$collection->toArray(true); // [['A', 'B', 'C'], [1]]
```

Convert JSON-Data into Objects (Collection)
-------------------------------------------

[](#convert-json-data-into-objects-collection)

```
namespace Arrayy\tests\Collection;

use Arrayy\Collection\AbstractCollection;

/**
 * @extends  AbstractCollection
 */
class UserDataCollection extends AbstractCollection
{
    /**
     * The type (FQCN) associated with this collection.
     *
     * @return string
     */
    public function getType()
    {
        return \Arrayy\tests\UserData::class;
    }
}

$json = '[{"id":1,"firstName":"Lars","lastName":"Moelleken","city":{"name":"Düsseldorf","plz":null,"infos":["lall"]}}, {"id":1,"firstName":"Sven","lastName":"Moelleken","city":{"name":"Köln","plz":null,"infos":["foo"]}}]';
$userDataCollection = UserDataCollection::createFromJsonMapper($json);

/** @var \Arrayy\tests\UserData[] $userDatas */
$userDataCollection->getAll();

$userData0 = $userDataCollection[0];
echo $userData0->firstName; // 'Lars'
$userData0->city; // CityData::class
echo $userData0->city->name; // 'Düsseldorf'

$userData1 = $userDataCollection[1];
echo $userData1->firstName; // 'Sven'
$userData1->city; // CityData::class
echo $userData1->city->name; // 'Köln'
```

Class methods
-------------

[](#class-methods)

##### use a "default object"

[](#use-a-default-object)

Creates an Arrayy object.

```
$arrayy = new Arrayy(array('fòô', 'bàř')); // Arrayy['fòô', 'bàř']
```

##### create(array $array) : Arrayy (Immutable)

[](#createarray-array--arrayy-immutable)

Creates an Arrayy object, via static "create()"-method

```
$arrayy = A::create(array('fòô', 'bàř')); // Arrayy['fòô', 'bàř']
```

##### createByReference(array &amp;$array) : Arrayy (Mutable)

[](#createbyreferencearray-array--arrayy-mutable)

WARNING: Creates an Arrayy object by reference.

```
$array = array('fòô', 'bàř');
$arrayy = A::createByReference($array); // Arrayy['fòô', 'bàř']
```

##### createFromJson(string $json) : Arrayy (Immutable)

[](#createfromjsonstring-json--arrayy-immutable)

Create an new Arrayy object via JSON.

```
$str = '{"firstName":"John", "lastName":"Doe"}';
$arrayy = A::createFromJson($str); // Arrayy['firstName' => 'John', 'lastName' => 'Doe']
```

##### createFromJsonMapper(string $json) : Arrayy (Immutable)

[](#createfromjsonmapperstring-json--arrayy-immutable)

Create an new Arrayy object via JSON and fill sub-objects is possible.

```
