PHPackages                             om/from-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. om/from-array

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

om/from-array
=============

fromArray trait allow create objects instances loaded with initial data array

v2.1.0(2mo ago)712.3k↓40%51BSD-3-ClausePHPPHP &gt;=8.1CI passing

Since Oct 27Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/OzzyCzech/fromArray)[ Packagist](https://packagist.org/packages/om/from-array)[ RSS](/packages/om-from-array/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (4)Versions (13)Used By (1)

[![Packagist Version](https://camo.githubusercontent.com/aed3fe955fe7494e6369eb7bf713d9360370ba2e894fab9c39a44d6320378d44/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f6d2f66726f6d2d61727261793f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/aed3fe955fe7494e6369eb7bf713d9360370ba2e894fab9c39a44d6320378d44/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f6d2f66726f6d2d61727261793f7374796c653d666f722d7468652d6261646765)[![Packagist License](https://camo.githubusercontent.com/4c6499dfde44481b69b1fa97e43d6419acbafe73a5b7959832ba891d27ceb294/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f6d2f66726f6d2d61727261793f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/4c6499dfde44481b69b1fa97e43d6419acbafe73a5b7959832ba891d27ceb294/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f6d2f66726f6d2d61727261793f7374796c653d666f722d7468652d6261646765)[![Packagist Downloads](https://camo.githubusercontent.com/65395a85b8e512bb08d93c27791ddcd4fe13b0b663ed754991110e7157e891a0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6f6d2f66726f6d2d61727261793f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/65395a85b8e512bb08d93c27791ddcd4fe13b0b663ed754991110e7157e891a0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6f6d2f66726f6d2d61727261793f7374796c653d666f722d7468652d6261646765)

`FromArray` Data Loader Trait
=============================

[](#fromarray-data-loader-trait)

`FromArray` is a lightweight PHP trait that enables effortless object hydration from associative arrays. It is especially useful in scenarios where data needs to be mapped into strongly-typed objects, such as when working with APIs, form inputs, or configuration data.

With support for PHP attributes, `FromArray` lets you fine-tune how each property is loaded, define type expectations, and apply custom transformation logic — all while keeping your code clean and expressive.

Install
-------

[](#install)

```
composer require om/from-array
```

Usage
-----

[](#usage)

The `FromArray` trait enables the creation of object instances preloaded with an initial data array:

```
class Example {
  use FromArray;
  public string $a;
  public string $b;
  public string $c;
}

$example = Example::fromArray(
  [
    'a' => 'value of A',
    'b' => 'value of B',
    'c' => 'value of C',
  ],
);

echo json_encode($example, JSON_PRETTY_PRINT);
```

Result:

```
{
  "a": "value of A",
  "b": "value of B",
  "c": "value of C"
}
```

The trait **works with public properties only** — private and protected properties will be ignored.

Attributes
----------

[](#attributes)

There are several [PHP Attributes](https://www.php.net/manual/en/language.attributes.overview.php) to configure the `fromArray` behavior:

### `Property`

[](#property)

The `Property` attribute allows you to map a specific key (`from`) from the data array to the property:

```
class Example
{
    use FromArray;

    #[Property(from: '_id')]
    public int $id;
}

$example = Example::fromArray(['_id' => 123]);
assert($example->id === 123);
```

You can also customize the `loader` used to transform the data:

```
function addPrefix(mixed $value) {
    return 'PREFIX_' . $value;
}

class Example
{
    use FromArray;

    #[Property(loader: 'addPrefix')]
    public string $name;
}

$example = Example::fromArray(['name' => 'name']);
assert($example->name === 'PREFIX_name');
```

Loader can be the **name of a class**, an **object**, or any type of **callable**.

For more see [basic-example.php](/examples/basic-example.php).

### `Loader`

[](#loader)

The `Loader` attribute allows you to define a value loader for the entire class or for individual properties:

```
use DataLoader\Loader;
use DataLoader\Property;

class MyLoader {
    public function __invoke($value, Property $property) {
        return match ($property->name) {
            'id' => (int) $value,
            'names' => explode(',', $value),
            default => $value,
        };
    }
}

#[Loader(MyLoader::class)]
class Example
{
    use FromArray;
    public mixed $id = null;
    public array $names = [];
    public string $other = '';
}

$example = Example::fromArray([
    'id' => '123',
    'names' => 'John,Doe,Smith',
    'other' => 'value',
]);
```

For more see [loader-class.php](/examples/loader-class.php) or [loader-property.php](/examples/loader-property.php).

### `Type`

[](#type)

The `Type` attribute allows you to define a specific type for the property. Types are usually auto-detected, but you can force the type using the `Type` attribute:

```
class Example
{
    use FromArray;

    #[Type(name: Types::Int, allowNull: true)]
    public mixed $id;
}
```

There is one special case — you can specify `Types::ArrayOfObjects` to load an array of objects of the same class. The `class` parameter is required in this case:

```
class ExampleObject {
    public function __construct(public ?string $name = null) {}
}

class Example
{
    use FromArray;

    #[Type(name: Types::ArrayOfObjects, class: ExampleObject::class)]
    public array $objects = [];
}

$example = Example::fromArray([
    'objects' => [
        ['name' => 'John'],
        ['name' => 'Doe'],
    ],
]);
```

See [array-of-objects.php](/examples/array-of-objects.php) for more information.

Metadata
--------

[](#metadata)

The [`Metadata`](https://github.com/OzzyCzech/fromArray/blob/main/src/Metadata.php) object contains all the information about the class and its properties. It is a singleton, but you can load an instance from cache:

```
// prepare metadata
$metadata = new Metadata();
$metadata->resolve(Example::class, MyObject::class);
$data = $metadata->getArrayCopy();

// restore singleton data
Metadata::fromCache($data);
```

See [metadata-cache.php](/examples/metadata-cache.php) for more information.

Testing
-------

[](#testing)

```
composer test    # run tests
composer format  # run PHP CS Fixer
```

###  Health Score

56

—

FairBetter than 97% of packages

Maintenance84

Actively maintained with recent releases

Popularity31

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity79

Established project with proven stability

 Bus Factor1

Top contributor holds 92.5% 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 ~281 days

Recently: every ~92 days

Total

12

Last Release

80d ago

Major Versions

v0.0.5 → v1.0.02024-08-01

v1.0.1 → v2.0.02025-04-09

PHP version history (3 changes)v0.0.1PHP &gt;=5.6.0

v1.0.0PHP &gt;=8.0

1.x-devPHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/56ca26f8b97f82b2a0b3e32bf121a275be1139f461584b306cc095562ea91e50?d=identicon)[OzzyCzech](/maintainers/OzzyCzech)

---

Top Contributors

[![OzzyCzech](https://avatars.githubusercontent.com/u/105520?v=4)](https://github.com/OzzyCzech "OzzyCzech (62 commits)")[![tarikflz](https://avatars.githubusercontent.com/u/13560943?v=4)](https://github.com/tarikflz "tarikflz (5 commits)")

---

Tags

arrayhydratorphp

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/om-from-array/health.svg)

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

###  Alternatives

[mauserrifle/simresults

Simrace result reader for PHP

684.8k](/packages/mauserrifle-simresults)

PHPackages © 2026

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