---
title: "Array Project"
description: "Typed array readers, composable validation types and array transformations"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-11-15"
last_update: "2026-11-15"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/data/array"
---

# Derafu Array



---

## Introduction

Typed array reading, composable validation types and explicit array transformations in PHP

# Typed Array Reading and Transformations

[![GitHub](https://img.shields.io/badge/github-derafu%2Farray-blue?logo=github)](https://github.com/derafu/array)
![GitHub last commit](https://img.shields.io/github/last-commit/derafu/array/main)
![CI Workflow](https://github.com/derafu/array/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/array)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/array)
![Total Downloads](https://poser.pugx.org/derafu/array/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/array/d/monthly)

`derafu/array` reads array values with explicit types, writes nested arrays in place, and provides transformations for paths, numeric text, trees, tables and subsets, and finds repeated items. It requires PHP 8.5 or later, `derafu/value` and `derafu/translation`.

## Installation

```bash
composer require derafu/array
```

## Reading Untrusted Data

```php
use Derafu\Array\ArrayReader;

$reader = ArrayReader::fromValue(
    json_decode(&#039;{&quot;host&quot;:&quot;localhost&quot;,&quot;port&quot;:5432}&#039;, true),
    source: &#039;connection.json&#039;,
);

$host = $reader-&gt;requireString(&#039;host&#039;); // string
$port = $reader-&gt;getInt(&#039;port&#039;, 5432);  // int
```

`fromValue()` rejects a value that is not an array. Use `fromArray()` when the input is already typed as an array. Readers are immutable snapshots of array contents; objects stored inside an array remain the same objects.

Reading is strict: `&#039;5432&#039;` is not an integer. Use getAsXXX()/requireAsXXX() for explicit field conversions, or ArrayCaster for its recursive array operation. Date and backed-enum types also interpret their supported representations.

## Reading Nested Values

All typed getters and presence checks accept dot notation. An existing literal key matching the complete expression takes precedence over navigation.

```php
$reader = ArrayReader::fromArray([&#039;connection&#039; =&gt; [&#039;port&#039; =&gt; 5432]]);
$reader-&gt;requireInt(&#039;connection.port&#039;); // 5432
```

See [Readers](readers) for presence and validation rules, and [Paths](paths) for the same literal-key precedence when reading, setting and wrapping values.

## Writing Values

```php
use Derafu\Array\ArrayWriter;

$data = [&#039;order&#039; =&gt; [&#039;total&#039; =&gt; &#039;1190&#039;]];
$writer = ArrayWriter::fromReference($data);

$writer-&gt;set(&#039;order.paid&#039;, true);
$writer-&gt;getReader()-&gt;requireAsInt(&#039;order.total&#039;); // 1190
```

`ArrayWriter` writes in the array it receives by reference, with the same keys as the reader. See [Writers](writers).

## The Classes

All eight array utility classes live in `Derafu\Array`. Composable value types and scalar conversions come from [Derafu Value](https://www.derafu.dev/docs/data/value).

| Class | Purpose | Guide |
| --- | --- | --- |
| `ArrayReader` | Optional and required typed reads, nested readers and key presence. | [Readers](readers) |
| `ArrayWriter` | In-place writes: set, remove, append, merge, defaults and scopes of an array. | [Writers](writers) |
| `ArrayPath` | Nested access, dot notation, resolving a path into keys and wrapping a value in a list. | [Paths](paths) |
| `ArrayCaster` | Recursive value interpretation delegated to ValueParser, and replacement of given or blank values by `null`. | [Casting](casting) |
| `ArrayTree` | Parent-linked rows into trees and trees into outlines. | [Trees](trees) |
| `ArrayTable` | Columns into rows, pairs into maps and keys into columns. | [Tables](tables) |
| `ArrayCombinations` | Subsets of a list. | [Combinations](combinations) |
| `ArrayDuplicates` | Items of a list that repeat the values of another one. | [Duplicates](duplicates) |

`ArrayReader` is a `final readonly` object. `ArrayWriter` is a `final` object that writes in place in the array it holds by reference. The other array classes expose static transformations. Reader type arguments are instances of `Derafu\Value\ValueType`. Exceptions raised by the library&#039;s validation are translatable; see [Translations](translations).

## Lists, Maps and Arrays

| Type | Accepted keys |
| --- | --- |
| List | Consecutive integers starting at `0`. |
| Map | Strings only. Numeric strings that PHP converts to integer keys are rejected. |
| Array | Any PHP array keys: integers, strings or both, consecutive or not. |

Empty arrays are accepted by all three. Choose `arrayOf()` when positions or identifiers must be preserved without requiring a list. Reading a nested array as a reader does not require it to be a map.




---

## Readers

Optional and required typed reads, null handling, integer keys, nested readers, sparse collections and typed views of the whole array

# ArrayReader

```php
use Derafu\Array\ArrayReader;
use Derafu\Value\ValueType;

$reader = ArrayReader::fromArray([&#039;name&#039; =&gt; &#039;Alice&#039;, &#039;enabled&#039; =&gt; false]);
$reader-&gt;requireString(&#039;name&#039;); // &#039;Alice&#039;
$reader-&gt;getBool(&#039;enabled&#039;, true); // false
```

## Creating a Reader

| Factory | Input | Behavior |
| --- | --- | --- |
| `fromArray(array $data, ?string $source = null)` | An array. | Creates a reader at the root. |
| `fromValue(mixed $data, ?string $source = null, string $path = &#039;&#039;)` | Untrusted input. | Validates that it is an array, without converting it. |
| `new ArrayReader($data, $path = &#039;&#039;, $source = null)` | An array. | Creates a reader with an explicit path and source. |

`toArray()` returns the stored array. Changing the original array after creating a reader does not change the reader&#039;s array values. See [The Whole Array](#the-whole-array) to check its shape.

## Optional and Required Values

A missing key or a value of `null` uses the optional getter&#039;s default. A present value of another type throws. Falsy values such as `false`, `0`, `&#039;&#039;` and `[]` are preserved when they match the requested type.

| Optional method | Required method | Value |
| --- | --- | --- |
| `getString($key, $default = null)` | `requireString($key)` | String. |
| `getNonEmptyString($key)` | `requireNonEmptyString($key)` | String containing at least one non-whitespace character; returned without trimming. |
| `getInt($key, $default = null)` | `requireInt($key)` | Integer. |
| `getFloat($key, $default = null)` | `requireFloat($key)` | Float; stored integers are rejected. |
| `getNumber($key, $default = null)` | `requireNumber($key)` | Integer or float. |
| `getBool($key, $default = null)` | `requireBool($key)` | Boolean. |
| `getDateTime($key)` | `requireDateTime($key)` | `DateTimeInterface`; see [Value Types](https://www.derafu.dev/docs/data/value/types#dates). |
| `getObject($key, $class)` | `requireObject($key, $class)` | Instance of the class or interface; the return type is that class. |
| `getEnum($key, $class)` | `requireEnum($key, $class)` | Case of a backed enum, or its exact backing value; the return type is that enum. See [Backed Enums](types#backed-enums). |
| `getArray($key)` | `requireArray($key)` | Any array. |
| `getIndexed($key)` | `requireIndexed($key)` | Array with integer keys, preserving gaps and order. |
| `getIndexedOf($key, $type)` | `requireIndexedOf($key, $type)` | Integer-keyed array whose values are parsed by the supplied type. |
| `getMap($key)` | `requireMap($key)` | Array with string keys. |
| `getList($key)` | `requireList($key)` | Zero-based consecutive list. |
| `getStringList($key)` | `requireStringList($key)` | List of strings. |
| `getIntList($key)` | `requireIntList($key)` | List of integers. |
| `getScalarList($key)` | `requireScalarList($key)` | List of booleans, numbers or strings. |
| `getArrayOf($key, $type)` | `requireArrayOf($key, $type)` | Array whose values match a type; keys are preserved. |
| `getMapOf($key, $type)` | `requireMapOf($key, $type)` | String-keyed array whose values match a type. |
| `getListOf($key, $type)` | `requireListOf($key, $type)` | List whose values match a type. |

Optional methods return `null` when there is no value or default. The primitive getters with a non-null default have a non-null return type for PHPStan. Required methods reject missing keys and `null`, including when the requested `ValueType` is nullable.

The generic methods accept any [composable type](types):

```php
$reader = ArrayReader::fromArray([&#039;mode&#039; =&gt; &#039;fast&#039;]);
$reader-&gt;get(&#039;mode&#039;, ValueType::literal(&#039;fast&#039;, &#039;safe&#039;), &#039;safe&#039;);
$reader-&gt;require(&#039;mode&#039;, ValueType::string());
$reader-&gt;get(&#039;tags&#039;, ValueType::listOf(ValueType::string()), []);
```

Defaults are returned as supplied, not validated or converted by the requested type.

Conversion variants exist only where a conversion exists: scalars (see below). Objects, arrays, dates and enums have no `getAsXXX()` variant: an object is never built from another value, and dates and enums already interpret their supported input forms.

## Indexed Arrays

The indexed family delegates to `ValueType::indexed()` and `indexedOf()`. Integer
keys may start anywhere, be negative, or have gaps. Lists and empty arrays are
accepted. String keys are rejected without conversion. PHP itself normalizes
some numeric string keys to integers when the input array is created.

```php
$reader = ArrayReader::fromArray([
    &#039;rows&#039; =&gt; [8 =&gt; [&#039;quantity&#039; =&gt; &#039;12.0&#039;], 2 =&gt; [&#039;quantity&#039; =&gt; &#039;1e3&#039;]],
], &#039;report.json&#039;);

$reader-&gt;requireIndexed(&#039;rows&#039;); // The original rows and keys.
$reader-&gt;requireIndexedOf(&#039;rows&#039;, ValueType::mapOf(ValueType::toInt()));
// [8 =&gt; [&#039;quantity&#039; =&gt; 12], 2 =&gt; [&#039;quantity&#039; =&gt; 1000]]

$rows = $reader-&gt;requireIndexedReaders(&#039;rows&#039;, ValueType::map());
$rows[8]-&gt;requireAsInt(&#039;quantity&#039;); // 12
```

Optional reads return `null` for missing or null values; required reads throw
`MissingValueException`. Empty arrays return `[]`. Item types determine whether
values are validated strictly or explicitly converted. Readers and the input
array remain unchanged by these reads.

Errors preserve paths and sources, including a string key such as `rows.extra`
or a value such as `rows.8.quantity`. The collection is not sorted or reindexed.

## Explicit Conversions

Strict getters validate existing types. The getAsXXX()/requireAsXXX() methods explicitly convert through ValueType and ValueCaster from [Derafu Value](https://www.derafu.dev/docs/data/value).

| Optional method | Required method | Converted type |
| --- | --- | --- |
| `getAsInt($key, $default = null)` | `requireAsInt($key)` | Integer. |
| `getAsFloat($key, $default = null)` | `requireAsFloat($key)` | Float. |
| `getAsNumber($key, $default = null)` | `requireAsNumber($key)` | Integer when possible, otherwise float. |
| `getAsBool($key, $default = null)` | `requireAsBool($key)` | Boolean. |
| `getAsString($key, $default = null)` | `requireAsString($key)` | String. |

```php
use Derafu\Array\ArrayReader;

$reader = ArrayReader::fromArray([&#039;port&#039; =&gt; &#039;5432&#039;, &#039;enabled&#039; =&gt; &#039;off&#039;, &#039;label&#039; =&gt; false]);
$reader-&gt;requireAsInt(&#039;port&#039;);       // 5432
$reader-&gt;requireAsBool(&#039;enabled&#039;);   // false
$reader-&gt;requireAsString(&#039;label&#039;);   // &#039;0&#039;
$reader-&gt;getAsNumber(&#039;missing&#039;, 0);  // 0
```

Missing keys and null retain the reader&#039;s existing default/required rules. Present values that cannot be converted throw; they do not use the default. See [ValueCaster&#039;s conversion contracts](https://www.derafu.dev/docs/data/value/casting).

## The Whole Array

The typed reads above take a key. To check the reader&#039;s own array, use `to()` with any [composable type](types), or one of its shortcuts. They mirror `get()`, `getMap()`, `getIndexed()` and `getList()`, and they throw `TypeMismatchException` when the array is not of the type.

| Method | Returns |
| --- | --- |
| `toArray()` | The stored array, unchecked: `array&lt;array-key, mixed&gt;`. |
| `toMap()` | The array when every key is a string: `array&lt;string, mixed&gt;`. |
| `toIndexed()` | The array when every key is an integer: `array&lt;int, mixed&gt;`. |
| `toList()` | The array when it is a consecutive list: `list&lt;mixed&gt;`. |
| `to($type)` | The array checked by any type, such as `ValueType::mapOf(ValueType::int())`. |

```php
$reader = ArrayReader::fromArray([&#039;name&#039; =&gt; &#039;Alice&#039;, &#039;age&#039; =&gt; 30]);
$reader-&gt;toMap(); // [&#039;name&#039; =&gt; &#039;Alice&#039;, &#039;age&#039; =&gt; 30]
$reader-&gt;to(ValueType::mapOf(ValueType::scalar()));

ArrayReader::fromArray([&#039;a&#039;, &#039;b&#039;])-&gt;toMap();
// Throws: The key &quot;$&quot; must be of type map, array given.
```

An empty array is accepted as a map, an indexed array and a list. Numeric string keys, which PHP stores as integers, are not map keys. The error says `$` for a reader at the root; for a nested reader it carries the reader&#039;s path and source, as in `The key &quot;rows.0&quot; of order.json must be of type map, array given.`

## Presence and Allowed Keys

Every read accepts an integer or string key. An existing literal key takes precedence; otherwise, dot notation such as `&#039;connection.port&#039;` navigates nested arrays.

| Method | Meaning |
| --- | --- |
| `hasKey($key)` | The key exists, even when its value is `null`. |
| `hasValue($key)` | The key exists and its value is not `null`. |
| `assertOnlyKeys(...$keys)` | Throws for any key not allowed; returns the same reader. It does not require the allowed keys to exist. |

```php
$reader = ArrayReader::fromArray([0 =&gt; null, &#039;enabled&#039; =&gt; false]);
$reader-&gt;hasKey(0); // true
$reader-&gt;hasValue(0); // false
$reader-&gt;hasValue(&#039;enabled&#039;); // true
$reader-&gt;assertOnlyKeys(0, &#039;enabled&#039;);
```

Integer allowed keys and their equivalent string forms are accepted by `assertOnlyKeys()`. This method checks actual keys at the current level; allowed names are literal and are not expanded into paths. To check nested keys, obtain a nested reader and call `assertOnlyKeys()` on it.

## Nested Readers and Collections

`getReader()` and `requireReader()` read any nested array as another reader: maps, lists and sparse arrays all work. An optional second argument validates the selected array with a `ValueType` before creating its reader. Omitting it, or passing `null`, accepts any array as before.

```php
$reader = ArrayReader::fromArray([&#039;authors&#039; =&gt; [[&#039;Alice&#039;, &#039;alice&#039;]]]);
$author = $reader-&gt;requireReader(&#039;authors&#039;)-&gt;requireReader(0);
$author-&gt;requireString(0); // &#039;Alice&#039;
$author-&gt;getString(1); // &#039;alice&#039;
```

| Optional | Required | Outer collection |
| --- | --- | --- |
| `getReaders($key)` | `requireReaders($key)` | A list of arrays, returned as a list of readers. |
| `getArrayReaders($key)` | `requireArrayReaders($key)` | An array of arrays, preserving arbitrary keys. |
| `getIndexedReaders($key)` | `requireIndexedReaders($key)` | An integer-keyed array of arrays, preserving gaps and row order. |

Each record can itself be any array. The collection methods also accept an optional second `ValueType` argument: it validates each record without changing the outer collection&#039;s requirements. `getReaders()` and `requireReaders()` still require a consecutive list; `getArrayReaders()` and `requireArrayReaders()` preserve arbitrary keys; `getIndexedReaders()` and `requireIndexedReaders()` require integer keys without reindexing.

Optional methods return `null` for absent or null values without invoking the type. Required methods throw `MissingValueException` for those values before invoking it. Empty collections return `[]`.

```php
use Derafu\Array\ArrayReader;
use Derafu\Value\ValueType;

$reader = ArrayReader::fromArray([
    &#039;innerJoin&#039; =&gt; [&#039;table&#039; =&gt; &#039;stock&#039;, &#039;condition&#039; =&gt; &#039;products.id = stock.product_id&#039;],
    &#039;questions&#039; =&gt; [[&#039;text&#039; =&gt; &#039;What is PHP?&#039;]],
]);

$join = $reader-&gt;requireReader(&#039;innerJoin&#039;, ValueType::map());
$table = $join-&gt;requireString(&#039;table&#039;); // &#039;stock&#039;.
$questions = $reader-&gt;requireReaders(&#039;questions&#039;, ValueType::map());
$text = $questions[0]-&gt;requireString(&#039;text&#039;); // &#039;What is PHP?&#039;.
```

The supplied type must produce an array. Examples include `ValueType::map()`, `ValueType::list()`, `ValueType::arrayOf()` and `ValueType::mapOf()`. Scalar-producing types are not valid arguments. A map requires string keys; a positional list is rejected when a map is requested.

Each selected array is parsed once during reader creation, and the parsed result becomes the child reader&#039;s data. Explicit conversion types can therefore prepare a reader&#039;s values without modifying the parent reader. Both validation errors and subsequent child reads retain the full path and source.

```php
use Derafu\Array\ArrayReader;
use Derafu\Value\ValueType;

$reader = ArrayReader::fromArray([
    &#039;translations&#039; =&gt; [
        &#039;es&#039; =&gt; [&#039;save&#039; =&gt; &#039;Guardar&#039;],
        &#039;en&#039; =&gt; [&#039;save&#039; =&gt; &#039;Save&#039;],
    ],
]);

$languages = $reader-&gt;requireArrayReaders(
    &#039;translations&#039;,
    ValueType::mapOf(ValueType::string()),
);
$label = $languages[&#039;es&#039;]-&gt;requireString(&#039;save&#039;); // &#039;Guardar&#039;.
```

```php
$reader = ArrayReader::fromValue(
    [&#039;rows&#039; =&gt; [3 =&gt; [&#039;name&#039; =&gt; &#039;Alice&#039;], 8 =&gt; [&#039;name&#039; =&gt; 123]]],
    source: &#039;account API&#039;,
    path: &#039;response&#039;,
);

$rows = $reader-&gt;requireArrayReaders(&#039;rows&#039;);
$rows[3]-&gt;requireString(&#039;name&#039;); // &#039;Alice&#039;
$rows[8]-&gt;requireString(&#039;name&#039;);
// Throws: The key &quot;response.rows.8.name&quot; of account API must be of type string, int given.
```

`requireReaders(&#039;rows&#039;)` would reject this outer collection because its keys are not a consecutive list. No reader reindexes an arbitrary collection.




---

## Writers

Write nested arrays in place, create levels, remove keys, append to lists, merge values and defaults, and write in a scope of the array

# ArrayWriter

`ArrayWriter` writes the keys of an array in place, as many times as needed. It is the counterpart of [`ArrayReader`](readers): it takes keys the same way and reports errors with the same messages and paths.

```php
use Derafu\Array\ArrayWriter;

$data = [&#039;order&#039; =&gt; [&#039;totals&#039; =&gt; [&#039;net&#039; =&gt; 1000]]];
$writer = ArrayWriter::fromReference($data);

$writer-&gt;set(&#039;order.id&#039;, 10);
$writer-&gt;getWriter(&#039;order.totals&#039;)-&gt;set(&#039;total&#039;, 1190);

// $data is now:
// [&#039;order&#039; =&gt; [&#039;totals&#039; =&gt; [&#039;net&#039; =&gt; 1000, &#039;total&#039; =&gt; 1190], &#039;id&#039; =&gt; 10]]
```

## Creating a Writer

| Factory | Input | Behavior |
| --- | --- | --- |
| `fromReference(array &amp;$data, ?string $source = null)` | A variable holding an array. | Creates a writer at the root that writes in that variable. |
| `new ArrayWriter($data, $path = &#039;&#039;, $source = null)` | A variable holding an array. | Creates a writer with an explicit path and source. |

The writer does not copy the array: every write changes the variable it was created from. `source` tells whoever reads an error which array it is (a file, a request, a document), as in `ArrayReader::fromArray()`, and `path` says where the array is inside a bigger one.

`toArray()` returns the current array.

## Writing

| Method | Behavior |
| --- | --- |
| `set($key, $value)` | Sets a value, creating the levels that are missing. |
| `remove($key)` | Removes a key. If the path does not exist, nothing happens. |
| `append($key, $value)` | Adds a value at the end of the list at the key. The list is created if the key is absent or `null`. |
| `merge($values)` | Merges recursively: the values replace what is already there. |
| `mergeDefaults($defaults)` | Merges recursively: what is already there is kept and the defaults only fill what is missing. |

All of them return the writer, so calls can be chained. Values are not typed when written: `null` is stored as `null`, and the type is what the reader asks for when the value is read.

```php
$data = [&#039;items&#039; =&gt; [&#039;a&#039;]];
$writer = ArrayWriter::fromReference($data);

$writer
    -&gt;append(&#039;items&#039;, &#039;b&#039;)
    -&gt;append(&#039;tags&#039;, &#039;new&#039;)
    -&gt;set(&#039;meta.owner&#039;, &#039;Alice&#039;)
    -&gt;remove(&#039;items.0&#039;);

// [&#039;items&#039; =&gt; [1 =&gt; &#039;b&#039;], &#039;tags&#039; =&gt; [&#039;new&#039;], &#039;meta&#039; =&gt; [&#039;owner&#039; =&gt; &#039;Alice&#039;]]
```

## Keys

Keys follow the rules of the reader and of [`ArrayPath`](paths): an existing literal key matching the complete string takes precedence; otherwise dots separate nested levels.

```php
$data = [&#039;profile.name&#039; =&gt; &#039;Alice&#039;];
$writer = ArrayWriter::fromReference($data);

$writer-&gt;set(&#039;profile.name&#039;, &#039;Bob&#039;); // writes the literal key
// [&#039;profile.name&#039; =&gt; &#039;Bob&#039;]
```

## Levels

`set()`, `append()` and `getWriter()` create the levels of the path that are absent or `null` as arrays. A level that exists and is not an array is an error: it is not replaced.

```php
$data = [&#039;order&#039; =&gt; [&#039;id&#039; =&gt; 33]];
ArrayWriter::fromReference($data, &#039;document&#039;)-&gt;set(&#039;order.id.x&#039;, 1);
// TypeMismatchException:
// The key &quot;order.id&quot; of document must be of type array, int given.
```

`append()` also requires the value at the key to be a list. `remove()` never fails: a path that does not exist, or that goes through a value that is not an array, has nothing to remove.

## Merging

`merge()` and `mergeDefaults()` use the semantics of `array_replace_recursive()`: nested arrays are merged by key, lists are merged by index and not concatenated, and `null` counts as a value.

```php
$data = [&#039;a&#039; =&gt; [&#039;x&#039; =&gt; 1, &#039;y&#039; =&gt; 2]];
$writer = ArrayWriter::fromReference($data);

$writer-&gt;merge([&#039;a&#039; =&gt; [&#039;y&#039; =&gt; 20, &#039;z&#039; =&gt; 30]]);
// [&#039;a&#039; =&gt; [&#039;x&#039; =&gt; 1, &#039;y&#039; =&gt; 20, &#039;z&#039; =&gt; 30]]

$writer-&gt;mergeDefaults([&#039;a&#039; =&gt; [&#039;x&#039; =&gt; 0, &#039;w&#039; =&gt; 4]]);
// [&#039;a&#039; =&gt; [&#039;x&#039; =&gt; 1, &#039;w&#039; =&gt; 4, &#039;y&#039; =&gt; 20, &#039;z&#039; =&gt; 30]]
```

Unlike `set()`, they do not fail when a scalar meets an array: the value that is merged in replaces it in `merge()`, and the existing value is kept in `mergeDefaults()`.

## Writing in a Scope

`getWriter($key)` returns a writer over the array at a key. What it writes is written in the array it comes from. The levels that are missing are created as arrays, so, unlike `ArrayReader::getReader()`, it never returns `null`.

```php
$data = [];
$writer = ArrayWriter::fromReference($data);

$totals = $writer-&gt;getWriter(&#039;order.totals&#039;);
$totals-&gt;set(&#039;net&#039;, 1000);
$totals-&gt;mergeDefaults([&#039;tax&#039; =&gt; 0, &#039;exempt&#039; =&gt; 0]);

// [&#039;order&#039; =&gt; [&#039;totals&#039; =&gt; [&#039;net&#039; =&gt; 1000, &#039;tax&#039; =&gt; 0, &#039;exempt&#039; =&gt; 0]]]
```

The writer of a scope knows its path from the root, so its errors and the reader it gives say the full path (`order.totals.net`).

The writer of a scope keeps a PHP reference to its level. While it is alive, copies of the array it writes in share that level.

## Reading What Was Written

The writer does not read. `getReader()` returns an [`ArrayReader`](readers) over the current data of the writer, with its path and source. It is a snapshot: ask for a new one after writing to read what was written.

```php
$data = [&#039;order&#039; =&gt; [&#039;total&#039; =&gt; &#039;1190&#039;]];
$writer = ArrayWriter::fromReference($data);

$writer-&gt;set(&#039;order.paid&#039;, true);
$writer-&gt;getReader()-&gt;requireAsInt(&#039;order.total&#039;); // 1190
$writer-&gt;getReader()-&gt;requireBool(&#039;order.paid&#039;);   // true
```

## Writer or ArrayPath

`ArrayPath::set()` is for a single write: it returns a new array and leaves its input unchanged. Use `ArrayWriter` when an array is written several times, or when the writes happen at different levels of the same array.




---

## Value Types

Compose Derafu Value types for optional and required array reads

# Value Types in Array Readers

ArrayReader accepts `Derafu\Value\ValueType&lt;T&gt;` for generic reads and collections. The type system belongs to [Derafu Value](https://www.derafu.dev/docs/data/value/types), including primitive checks, explicit conversions, dates, backed enums, unions, nullable types and custom types.

```php
use Derafu\Array\ArrayReader;
use Derafu\Value\ValueType;

$reader = ArrayReader::fromArray([
    &#039;quantities&#039; =&gt; [3 =&gt; &#039;12.0&#039;, 8 =&gt; &#039;2&#039;],
    &#039;mode&#039; =&gt; &#039;fast&#039;,
], &#039;settings.php&#039;);

$reader-&gt;requireIndexedOf(&#039;quantities&#039;, ValueType::toInt());
// [3 =&gt; 12, 8 =&gt; 2]

$reader-&gt;get(&#039;mode&#039;, ValueType::literal(&#039;fast&#039;, &#039;safe&#039;), &#039;safe&#039;);
// &#039;fast&#039;
```

## Validation and Conversion

`ValueType::int()` checks an existing integer; `ValueType::toInt()` requests conversion through ValueCaster. Built-in getters delegate to these same types: requireInt() is strict, while requireAsInt() converts explicitly. PHPStan follows the generic return type through these operations.

Arrays preserve arbitrary integer/string keys. Indexed arrays require integer keys and preserve gaps and order. Maps require string keys; lists require consecutive integer keys starting at zero. Empty collections are accepted. A type such as mapOf() checks every value, not a schema of required field names.

## Nullability and Presence

A nullable type accepts null when parsed directly, but reader methods apply their own presence rules first: optional reads return the default for a missing or null key, and required reads reject both. `hasKey()` distinguishes a present null key from a missing key.

```php
use Derafu\Array\ArrayReader;
use Derafu\Value\ValueType;

$reader = ArrayReader::fromArray([&#039;count&#039; =&gt; null]);
$reader-&gt;get(&#039;count&#039;, ValueType::toInt()-&gt;nullable(), 0); // 0
$reader-&gt;hasKey(&#039;count&#039;);   // true
$reader-&gt;hasValue(&#039;count&#039;); // false
```

## Backed Enums

```php
use Derafu\Array\ArrayReader;
use Derafu\Value\ValueType;

enum Status: string
{
    case Pending = &#039;pending&#039;;
    case Approved = &#039;approved&#039;;
}

$reader = ArrayReader::fromArray([&#039;status&#039; =&gt; &#039;approved&#039;]);
$reader-&gt;require(&#039;status&#039;, ValueType::backedEnum(Status::class));
// Status::Approved
```

`getEnum()` and `requireEnum()` are shortcuts for the same type and return the enum class given:

```php
$reader-&gt;requireEnum(&#039;status&#039;, Status::class); // Status::Approved
$reader-&gt;getEnum(&#039;missing&#039;, Status::class);    // null
```

Backing values use their exact int/string type, without scalar coercion. See [ValueType](https://www.derafu.dev/docs/data/value/types) for enum factories, dates, custom type callbacks and union order.

## Error Context

ValueType reports the full nested path and the expected element type. ArrayReader adapts a value type mismatch to `Derafu\Array\Exception\TypeMismatchException`, preserving the Value exception as its cause. The reader keeps its own translated key-oriented messages and source context. See [Translations](translations).




---

## Paths

Read and update nested arrays, transform dot notation and wrap values in lists

# ArrayPath

`ArrayPath` provides static operations over nested arrays. The transformations return arrays without modifying their input. To write several times in the same array, in place, see [Writers](writers).

```php
use Derafu\Array\ArrayPath;

$data = [&#039;customer&#039; =&gt; [&#039;name&#039; =&gt; &#039;Alice&#039;, &#039;note&#039; =&gt; null]];
ArrayPath::get($data, &#039;customer.name&#039;); // &#039;Alice&#039;
ArrayPath::get($data, [&#039;customer&#039;, &#039;note&#039;], &#039;default&#039;); // null
ArrayPath::get($data, &#039;customer.missing&#039;, &#039;default&#039;); // &#039;default&#039;

$updated = ArrayPath::set($data, &#039;customer.address.city&#039;, &#039;Santiago&#039;);
// The original $data is unchanged.
```

## Reading and Setting Paths

`get($array, $path, $default = null)`, `set($array, $path, $value)` and `wrap($array, $path)` accept a dot-separated string or a non-empty list of string segments.

`get()` returns a stored `null` unchanged. Its default is used when a key is absent or an intermediate level is not an array. `set()` creates missing levels and replaces non-array intermediate values with arrays.

For a string path, all three methods first use an existing literal key matching the complete string. Only when that key is absent do dots separate nested levels. A literal key with a null value still takes precedence.

```php
$data = [
    &#039;profile.name&#039; =&gt; &#039;Alice&#039;,
    &#039;profile&#039; =&gt; [&#039;name&#039; =&gt; &#039;Nested&#039;],
];

ArrayPath::get($data, &#039;profile.name&#039;); // &#039;Alice&#039;

$updated = ArrayPath::set($data, &#039;profile.name&#039;, &#039;Bob&#039;);
// [&#039;profile.name&#039; =&gt; &#039;Bob&#039;, &#039;profile&#039; =&gt; [&#039;name&#039; =&gt; &#039;Nested&#039;]]
ArrayPath::get($updated, &#039;profile.name&#039;); // &#039;Bob&#039;
```

When the literal key is absent, `set()` creates or updates the nested path. Its interpretation therefore depends on the existing keys, including when starting from an empty array:

```php
ArrayPath::set([], &#039;profile.name&#039;, &#039;Bob&#039;);
// [&#039;profile&#039; =&gt; [&#039;name&#039; =&gt; &#039;Bob&#039;]]
```

Literal matching applies to the complete string at the supplied array&#039;s root. After falling back to navigation, dots separate individual segments. Segment lists describe an explicit sequence of keys, including intermediate keys containing dots:

```php
ArrayPath::get([&#039;a.b&#039; =&gt; [&#039;c&#039; =&gt; 1]], [&#039;a.b&#039;, &#039;c&#039;]); // 1
ArrayPath::get([&#039;items&#039; =&gt; [[&#039;id&#039; =&gt; 7]]], &#039;items.0.id&#039;); // 7
```

`get()` returns `mixed`; use `ArrayReader` or `ValueType` when values must be validated.

## Resolving a Path

`keys($array, $path)` returns the keys that a path names in a given array, with the same rule that `get()`, `set()`, `wrap()`, `ArrayReader` and `ArrayWriter` follow: an existing literal key matching the complete string is a single key; otherwise the string is split by its dots. A list of segments is returned as it is.

```php
ArrayPath::keys([&#039;a.b&#039; =&gt; 1], &#039;a.b&#039;); // [&#039;a.b&#039;]
ArrayPath::keys([], &#039;a.b.c&#039;);          // [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]
ArrayPath::keys([], [&#039;a.b&#039;, &#039;c&#039;]);     // [&#039;a.b&#039;, &#039;c&#039;]
```

## Flat and Nested Forms

```php
ArrayPath::flatten([&#039;a&#039; =&gt; [&#039;b&#039; =&gt; 1, &#039;c&#039; =&gt; [2, 3]]]);
// [&#039;a.b&#039; =&gt; 1, &#039;a.c.0&#039; =&gt; 2, &#039;a.c.1&#039; =&gt; 3]

ArrayPath::flatten([&#039;b&#039; =&gt; 1], &#039;a&#039;);
// [&#039;a.b&#039; =&gt; 1]

ArrayPath::expand([&#039;a.b&#039; =&gt; 1, &#039;a.c&#039; =&gt; 2, &#039;d&#039; =&gt; 3]);
// [&#039;a&#039; =&gt; [&#039;b&#039; =&gt; 1, &#039;c&#039; =&gt; 2], &#039;d&#039; =&gt; 3]
```

`expand()` keeps integer keys at the current level and replaces conflicting scalar levels when a later path needs an array. `flatten()` emits leaf values; empty nested arrays produce no entry. Dots in literal keys are not escaped. These transformations are not a lossless round trip for every possible array.

## Wrapping a Value

`wrap()` places a value in a one-element list unless it is already a list. It uses `array_is_list()`: having a key `0` alone does not make an array a list.

```php
ArrayPath::wrap([&#039;items&#039; =&gt; [&#039;name&#039; =&gt; &#039;Alice&#039;]], &#039;items&#039;);
// [&#039;items&#039; =&gt; [[&#039;name&#039; =&gt; &#039;Alice&#039;]]]

ArrayPath::wrap([&#039;items&#039; =&gt; [0 =&gt; &#039;a&#039;, 2 =&gt; &#039;b&#039;]], &#039;items&#039;);
// [&#039;items&#039; =&gt; [[0 =&gt; &#039;a&#039;, 2 =&gt; &#039;b&#039;]]]

ArrayPath::wrap([&#039;document.reference&#039; =&gt; [&#039;id&#039; =&gt; 123]], &#039;document.reference&#039;);
// [&#039;document.reference&#039; =&gt; [[&#039;id&#039; =&gt; 123]]]
```

As with `get()` and `set()`, an existing complete literal key takes precedence over the nested path. An empty array and an existing list are unchanged. A missing path, a null value at the target, or a non-array intermediate level is left unchanged. Assign the returned array when applying a transformation.




---

## Casting

Recursively interpret array values through ValueParser, or replace given or blank values by null

# ArrayCaster

`ArrayCaster` traverses array leaves and delegates each value directly to `Derafu\Value\ValueParser::parse()`. Its options and defaults match the parser:

```text
ArrayCaster::cast(
    array $array,
    bool $preserveNumericFormat = false,
    bool $preserveNumericPrecision = false,
): array
```

The returned array keeps its original keys and nesting. The supplied array is not modified. Empty nested arrays remain empty arrays. Scalar interpretation, Stringable conversion and unsupported values follow [ValueParser](https://www.derafu.dev/docs/data/value/parsing).

## Recursive Interpretation

```php
use Derafu\Array\ArrayCaster;

$input = [
    &#039;quantity&#039; =&gt; &#039;12.0&#039;,
    &#039;message&#039; =&gt; &#039; text &#039;,
    &#039;blank&#039; =&gt; &#039;   &#039;,
    &#039;empty&#039; =&gt; &#039;empty&#039;,
    &#039;nothing&#039; =&gt; &#039;(null)&#039;,
    &#039;nested&#039; =&gt; [3 =&gt; [&#039;enabled&#039; =&gt; &#039;off&#039;, &#039;zero&#039; =&gt; &#039;0&#039;]],
];

$result = ArrayCaster::cast($input);
// [
//     &#039;quantity&#039; =&gt; 12,
//     &#039;message&#039; =&gt; &#039; text &#039;,
//     &#039;blank&#039; =&gt; false,
//     &#039;empty&#039; =&gt; &#039;&#039;,
//     &#039;nothing&#039; =&gt; null,
//     &#039;nested&#039; =&gt; [3 =&gt; [&#039;enabled&#039; =&gt; false, &#039;zero&#039; =&gt; 0]],
// ]
```

There is no trimming or empty-value substitution before the parser. Unrecognized text keeps its spaces, while whitespace-only text becomes `false` through ValueCaster&#039;s boolean conversion. Integers are preferred when exact conversion is possible; numeric `&#039;0&#039;` and `&#039;1&#039;` therefore become integers rather than booleans.

Native numbers, booleans, nulls, resources and objects without Stringable remain unchanged. Stringable leaves are converted to text and interpreted using the same options. A failing Stringable conversion propagates Value&#039;s translatable `ValueConversionException` with its original cause.

## Preserving Numeric Format

Pass `preserveNumericFormat: true` to keep numeric text when converting the resulting number back to string would alter its original spelling:

```php
use Derafu\Array\ArrayCaster;

ArrayCaster::cast(
    [&#039;a&#039; =&gt; &#039;12&#039;, &#039;b&#039; =&gt; &#039;19.90&#039;, &#039;c&#039; =&gt; &#039;007&#039;, &#039;d&#039; =&gt; &#039;1e3&#039;, &#039;e&#039; =&gt; &#039; 12 &#039;],
    preserveNumericFormat: true,
);
// [&#039;a&#039; =&gt; 12, &#039;b&#039; =&gt; &#039;19.90&#039;, &#039;c&#039; =&gt; &#039;007&#039;, &#039;d&#039; =&gt; &#039;1e3&#039;, &#039;e&#039; =&gt; &#039; 12 &#039;]
```

Exterior whitespace and decimal trailing zeros are part of the original spelling. This option concerns numeric text; special literals and boolean words are still interpreted normally.

## Preserving Numeric Precision

Pass `preserveNumericPrecision: true` to retain numeric text when the parser detects lost significant decimal digits or a non-finite result:

```php
use Derafu\Array\ArrayCaster;

ArrayCaster::cast([&#039;large&#039; =&gt; &#039;1e400&#039;]);
// [&#039;large&#039; =&gt; INF]

ArrayCaster::cast(
    [&#039;large&#039; =&gt; &#039;1e400&#039;, &#039;small&#039; =&gt; &#039;1e-400&#039;, &#039;fraction&#039; =&gt; &#039;1.0000000000000000001&#039;],
    preserveNumericPrecision: true,
);
// [&#039;large&#039; =&gt; &#039;1e400&#039;, &#039;small&#039; =&gt; &#039;1e-400&#039;, &#039;fraction&#039; =&gt; &#039;1.0000000000000000001&#039;]
```

Both options may be enabled together. Their exact guarantees, including the distinction between significant decimal digits and exact binary representation, are defined by [ValueParser](https://www.derafu.dev/docs/data/value/parsing). ArrayCaster implements no separate numeric grammar or preservation rules.

## Replacing Values by Null

`ArrayCaster::nullify()` traverses array leaves and replaces by `null` those that are one of the given values:

```text
ArrayCaster::nullify(
    array $array,
    array $values,
): array
```

The list of values must have at least one value. The comparison is strict: `0` is not `false` and `&#039;0&#039;` is not `&#039;&#039;`. The returned array keeps its original keys and nesting, empty nested arrays remain empty arrays and the supplied array is not modified. The caller decides which values mean &quot;no value&quot;; the method knows no rule of its own.

```php
use Derafu\Array\ArrayCaster;

$input = [
    &#039;net&#039; =&gt; 100000,
    &#039;vat&#039; =&gt; false,
    &#039;name&#039; =&gt; &#039;&#039;,
    &#039;zero&#039; =&gt; 0,
    &#039;items&#039; =&gt; [[&#039;code&#039; =&gt; 1, &#039;amount&#039; =&gt; false]],
];

ArrayCaster::nullify($input, [false, &#039;&#039;]);
// [
//     &#039;net&#039; =&gt; 100000,
//     &#039;vat&#039; =&gt; null,
//     &#039;name&#039; =&gt; null,
//     &#039;zero&#039; =&gt; 0,
//     &#039;items&#039; =&gt; [[&#039;code&#039; =&gt; 1, &#039;amount&#039; =&gt; null]],
// ]
```

It prepares data for [ArrayReader](readers), where only `null` or a missing key is absent:

```php
$reader = ArrayReader::fromArray(ArrayCaster::nullify($input, [false, &#039;&#039;]));

$reader-&gt;getAsInt(&#039;vat&#039;, 0); // 0
```

## Replacing Blank Values by Null

`ArrayCaster::nullifyBlank()` replaces by `null` the values that [ValueInspector::isBlank()](https://www.derafu.dev/docs/data/value/inspection) considers blank: an empty string or an empty array.

```text
ArrayCaster::nullifyBlank(
    array $array,
): array
```

False, zero and whitespace-only strings are not blank, so they are kept. The arrays are traversed, but an array is blank only when it is empty: one that has only blank values is kept, with those values replaced by `null`. The returned array keeps its original keys and the supplied array is not modified.

```php
use Derafu\Array\ArrayCaster;

ArrayCaster::nullifyBlank([
    &#039;name&#039; =&gt; &#039;&#039;,
    &#039;tags&#039; =&gt; [],
    &#039;active&#039; =&gt; false,
    &#039;quantity&#039; =&gt; 0,
    &#039;nested&#039; =&gt; [&#039;code&#039; =&gt; &#039;&#039;, &#039;items&#039; =&gt; [&#039;&#039;]],
]);
// [
//     &#039;name&#039; =&gt; null,
//     &#039;tags&#039; =&gt; null,
//     &#039;active&#039; =&gt; false,
//     &#039;quantity&#039; =&gt; 0,
//     &#039;nested&#039; =&gt; [&#039;code&#039; =&gt; null, &#039;items&#039; =&gt; [null]],
// ]
```

Use `nullify()` to replace other values, such as `false` or a text that means &quot;no value&quot; in the source.

## Reading and Conversion

Use ArrayReader&#039;s strict getters to validate existing PHP types, or getAsXXX()/requireAsXXX() to convert individual fields. Use ArrayCaster when an entire array should be traversed. Recursive interpretation does not declare a required field schema or choose application defaults.




---

## Trees

Build parent-linked array trees and extract keyed outlines with nesting levels

# ArrayTree

## Rows into a Tree

`ArrayTree::fromRows($items, $parentField, $childrenField, $parentId = null)` uses the array keys as node identifiers. Each row&#039;s parent field refers to the key of its parent.

```php
use Derafu\Array\ArrayTree;

$items = [
    1 =&gt; [&#039;parent_id&#039; =&gt; null, &#039;name&#039; =&gt; &#039;root&#039;],
    2 =&gt; [&#039;parent_id&#039; =&gt; 1, &#039;name&#039; =&gt; &#039;child&#039;],
    3 =&gt; [&#039;parent_id&#039; =&gt; 2, &#039;name&#039; =&gt; &#039;leaf&#039;],
];

$tree = ArrayTree::fromRows($items, &#039;parent_id&#039;, &#039;children&#039;);
// [1 =&gt; [&#039;name&#039; =&gt; &#039;root&#039;, &#039;children&#039; =&gt; [
//     2 =&gt; [&#039;name&#039; =&gt; &#039;child&#039;, &#039;children&#039; =&gt; [
//         3 =&gt; [&#039;name&#039; =&gt; &#039;leaf&#039;, &#039;children&#039; =&gt; []],
//     ]],
// ]]]
```

Keys are preserved, parent fields are removed, and the children field is present even when empty. Parent comparisons are strict: integer `1` and string `&#039;1&#039;` are different parent values.

Rows without the parent field, and branches not reachable from the selected root parent, are omitted. Supply rows keyed by their identifiers; for database lists, `array_column($rows, null, &#039;id&#039;)` can prepare that structure.

## Tree into an Outline

`toOutline($tree, $nameField, $childrenField)` traverses depth first and returns each node&#039;s name and nesting level, keeping its key:

```php
ArrayTree::toOutline($tree, &#039;name&#039;, &#039;children&#039;);
// [
//     1 =&gt; [&#039;name&#039; =&gt; &#039;root&#039;, &#039;level&#039; =&gt; 0],
//     2 =&gt; [&#039;name&#039; =&gt; &#039;child&#039;, &#039;level&#039; =&gt; 1],
//     3 =&gt; [&#039;name&#039; =&gt; &#039;leaf&#039;, &#039;level&#039; =&gt; 2],
// ]
```

This is an outline, not a reconstruction of the original rows: other fields are not included. Node keys must be unique across the tree to avoid later nodes replacing earlier outline entries.

A non-array node or a node with a missing or null name is skipped with its descendants. A node whose children field is not an array is included, but those children are omitted. The optional `$level` and by-reference `$result` parameters support recursive accumulation; ordinary callers use the first three arguments.




---

## Tables

Transform column groups into rows, key-value pairs into arrays and row keys into columns

# ArrayTable

```php
use Derafu\Array\ArrayTable;
```

## Columns into Rows

`columnsToRows($array, $keys = null)` transposes column groups into rows. Columns are read at zero-based positions.

```php
ArrayTable::columnsToRows([&#039;name&#039; =&gt; [&#039;Alice&#039;, &#039;Bob&#039;], &#039;age&#039; =&gt; [30]]);
// [
//     [&#039;name&#039; =&gt; &#039;Alice&#039;, &#039;age&#039; =&gt; 30],
//     [&#039;name&#039; =&gt; &#039;Bob&#039;, &#039;age&#039; =&gt; null],
// ]

ArrayTable::columnsToRows([&#039;name&#039; =&gt; [&#039;Alice&#039;]], [&#039;name&#039;, &#039;email&#039;]);
// [[&#039;name&#039; =&gt; &#039;Alice&#039;, &#039;email&#039; =&gt; null]]
```

The longest selected column determines the number of rows. Missing positions and selected columns that do not exist supply `null`. If no selected column exists, the result is empty. With no `$keys`, every column is selected.

## Pairs into a Map

`pairsToMap($table)` requires each row to be an array with exactly two columns. The first column becomes the key and the second its value. Column order determines their role, including for rows with named columns.

```php
ArrayTable::pairsToMap([[&#039;name&#039;, &#039;Alice&#039;], [&#039;age&#039;, 30]]);
// [&#039;name&#039; =&gt; &#039;Alice&#039;, &#039;age&#039; =&gt; 30]
```

Keys may be scalar or null. Integers stay integers; other accepted keys are converted to strings before PHP applies its array-key rules. For example, `null` becomes `&#039;&#039;`, `true` becomes `&#039;1&#039;` (stored as integer `1`) and `2.7` becomes `&#039;2.7&#039;`.

Later duplicate keys replace earlier values. Invalid rows, or keys that are arrays, objects or resources, throw a translatable `Derafu\Array\Exception\ArrayException`, which extends `InvalidArgumentException`. Despite its name, this transformation can produce integer keys; use `ValueType::map()` separately if string-only keys are required.

## Row Keys into a Column

`withKeyColumn($data, $idField)` adds each row&#039;s array key as a column:

```php
ArrayTable::withKeyColumn([&#039;u1&#039; =&gt; [&#039;name&#039; =&gt; &#039;Alice&#039;], &#039;u2&#039; =&gt; [&#039;name&#039; =&gt; &#039;Bob&#039;]], &#039;id&#039;);
// [&#039;u1&#039; =&gt; [&#039;id&#039; =&gt; &#039;u1&#039;, &#039;name&#039; =&gt; &#039;Alice&#039;], &#039;u2&#039; =&gt; [&#039;id&#039; =&gt; &#039;u2&#039;, &#039;name&#039; =&gt; &#039;Bob&#039;]]
```

Outer keys are preserved. A row that already has the named column keeps its own value: the operation supplies a default identifier rather than overwriting it. All three transformations return new arrays.




---

## Combinations

Generate subsets of a list with a minimum number of elements

# ArrayCombinations

`ArrayCombinations::subsets($array, $minLength = 1)` enumerates subsets of a zero-based consecutive list. Each result is itself a list.

```php
use Derafu\Array\ArrayCombinations;

ArrayCombinations::subsets([1, 2, 3]);
// [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

ArrayCombinations::subsets([1, 2, 3], 2);
// [[1, 2], [1, 3], [2, 3], [1, 2, 3]]

ArrayCombinations::subsets([1, 2], 0);
// [[], [1], [2], [1, 2]]
```

Selection is by position, preserving the input order within each subset. Equal values at different positions can therefore produce equal-looking subsets. The input is unchanged.

The algorithm examines `2^n` combinations. By default it excludes the empty subset, returning `2^n - 1` results; a minimum length of zero includes it. Use small lists: raising the minimum length filters results but does not avoid examining the combinations.




---

## Duplicates

Find the items of a list that repeat the values of another one, comparing by paths at any level

# ArrayDuplicates

`ArrayDuplicates` finds the items of a list that repeat the values of an earlier item. What identifies an item are the values at the paths that are given, which can be at any level; without paths, the whole item is compared.

```php
use Derafu\Array\ArrayDuplicates;

$documents = [
    [&#039;TpoDoc&#039; =&gt; 33, &#039;NroDoc&#039; =&gt; 21],
    [&#039;TpoDoc&#039; =&gt; 33, &#039;NroDoc&#039; =&gt; 22],
    [&#039;TpoDoc&#039; =&gt; 61, &#039;NroDoc&#039; =&gt; 21],
    [&#039;TpoDoc&#039; =&gt; 33, &#039;NroDoc&#039; =&gt; 21],
];

ArrayDuplicates::find($documents, [&#039;TpoDoc&#039;, &#039;NroDoc&#039;]);
// [[&#039;index&#039; =&gt; 3, &#039;first&#039; =&gt; 0, &#039;value&#039; =&gt; [33, 21]]]
```

| Method | What it does |
| --- | --- |
| `find($items, $paths = [], $normalize = null)` | Every item that repeats an earlier one. |
| `first(...)` | The first one, or `null` if there is none. |
| `assertUnique(...)` | Throws `DuplicateValueException` for the first one. Returns nothing. |

## What Is Reported

Each repeated item is reported with three entries:

| Entry | Content |
| --- | --- |
| `index` | The key of the repeated item in the list, as it is in the list. |
| `first` | The key of the first item that has those values. |
| `value` | The values read from the repeated item, in the order of the paths, as they are (before normalizing them). |

The items are reported in the order of the list. An item that appears three times is reported twice, each one pointing to the first.

## Paths

A path is a string, an integer or a list of them, and it is read with [`ArrayPath::get()`](paths): a key, dot notation (`&#039;Encabezado.IdDoc.Folio&#039;`) or the levels as a list (`[&#039;Encabezado&#039;, &#039;IdDoc&#039;, &#039;Folio&#039;]`). Paths of different levels can be mixed in the same call.

```php
ArrayDuplicates::find($items, [&#039;a&#039;, &#039;b.c&#039;]);
```

A path that is not in an item gives `null`, so two items that do not have it have the same value for it. An item that is an object is read through its public properties. An item that is neither an array nor an object can not be read by paths and is an `ArrayException`, as is a path that is not valid.

Without paths the whole item is compared, whatever it is: an array, an object or a scalar.

## Comparison

Two items are the same when their values have the same type and the same value: `&#039;1&#039;` and `1` are different. The values must be serializable; one that is not (a closure, for instance) is an `ArrayException` that tells which item has it.

To compare in another way, pass `$normalize`, a `callable(mixed): mixed` that is applied to each value that is read before comparing it:

```php
$normalize = static fn (mixed $value): string =&gt; (string) (int) trim((string) $value);

ArrayDuplicates::find([[&#039;n&#039; =&gt; 21], [&#039;n&#039; =&gt; &#039;0021&#039;], [&#039;n&#039; =&gt; &#039; 21 &#039;]], [&#039;n&#039;], $normalize);
// [
//     [&#039;index&#039; =&gt; 1, &#039;first&#039; =&gt; 0, &#039;value&#039; =&gt; [&#039;0021&#039;]],
//     [&#039;index&#039; =&gt; 2, &#039;first&#039; =&gt; 0, &#039;value&#039; =&gt; [&#039; 21 &#039;]],
// ]
```

The items are compared in one pass, so the time grows with the size of the list.

## Requiring Unique Items

`assertUnique()` is for who only needs to know that there are no repeated items. Like [`assertOnlyKeys()`](readers), it checks a property of the whole data and throws a specific exception:

```php
use Derafu\Array\Exception\DuplicateValueException;

try {
    ArrayDuplicates::assertUnique($documents, [&#039;TpoDoc&#039;, &#039;NroDoc&#039;]);
} catch (DuplicateValueException $exception) {
    echo $exception-&gt;getMessage();
    // The item with key 3 repeats the item with key 0 (TpoDoc = 33, NroDoc = 21).

    $exception-&gt;getIndex();  // 3
    $exception-&gt;getFirst();  // 0
    $exception-&gt;getValues(); // [33, 21]
}
```

`DuplicateValueException` extends `ArrayException` and carries the key of the repeated item, the key of the first one and the values, so whoever catches it can say it in its own words. The message names the items by their key in the list, which can be a number or a text, and shows each path with the value that is repeated. Without paths it is `The item with key {index} is the same as the item with key {first}.` See [Translations](translations) for its messages.




---

## Translations

Translate array validation errors and register the package resource provider

# Translations

Errors from ArrayReader, ArrayTable and ArrayDuplicates belong to `Derafu\Array\Exception\ArrayException`, which extends `Derafu\Translation\Exception\Logic\TranslatableInvalidArgumentException`. MissingValueException, TypeMismatchException and UnexpectedKeyException specialize array read failures, and DuplicateValueException the items that repeat the values of another one. They can be caught as PHP&#039;s `InvalidArgumentException` and translated through [Derafu Translation](https://www.derafu.dev/docs/core/translation).

```php
use Derafu\Array\ArrayReader;

try {
    ArrayReader::fromArray([&#039;port&#039; =&gt; &#039;abc&#039;], &#039;settings.php&#039;)-&gt;requireInt(&#039;port&#039;);
} catch (InvalidArgumentException $exception) {
    echo $exception-&gt;getMessage();
    // The key &quot;port&quot; of settings.php must be of type int, string given.
}
```

ArrayCaster delegates to ValueParser and propagates its ValueConversionException when Stringable conversion fails. Register Value&#039;s provider when translating those exceptions; see [Value Translations](https://www.derafu.dev/docs/data/value/translations).

## Messages and Context

| Message | Cause |
| --- | --- |
| `The key &quot;{key}&quot; must be of type {expected}, {given} given.` | A value has an invalid type. |
| `The key &quot;{key}&quot; is required.` | A required read finds a missing or null value. |
| `The key &quot;{key}&quot; is not allowed; the allowed keys are: {allowed}.` | `assertOnlyKeys()` finds an unexpected key. |
| `The item with key {index} repeats the item with key {first} ({values}).` | `assertUnique()` finds a repeated item that was compared by paths; `{values}` has each path with its value (`TpoDoc = 33, NroDoc = 21`). |
| `The item with key {index} is the same as the item with key {first}.` | `assertUnique()` finds a repeated item that was compared whole. |
| `The path {position} must be a string, an integer or a list of them, {given} given.` | A path of ArrayDuplicates is not valid. |
| `The item with key {index} must be an array or an object to read {paths}, {given} given.` | ArrayDuplicates reads paths from an item that is neither. |
| `The values of the item with key {index} can not be compared: {reason}.` | A value of an item can not be serialized to be compared. |
| `Row {index} must have exactly 2 columns.` | `pairsToMap()` finds an invalid row. |
| `The first column of row {index} must be a scalar or null to be a key.` | A pair has an invalid key value. |

Reader and type messages also have variants containing `of {source}`. Nested readers retain the source and append their keys to the diagnostic path. Expected type names come from ValueType; `map` refers to string-keyed arrays. ArrayReader wraps Value type mismatches while preserving their nested path, element type and original cause. Direct ValueType calls use the [Value exception contract](https://www.derafu.dev/docs/data/value/translations).

## Resource Provider

The package ships Spanish translations in `resources/translations/errors+intl-icu.es.php`, with the provider `Derafu\Array\Translation\ArrayTranslationResourceProvider`.

```php
use Derafu\Array\Translation\ArrayTranslationResourceProvider;
use Derafu\Translation\TranslatorFactory;

$translator = TranslatorFactory::create(
    defaultLocale: &#039;es&#039;,
    fallbackLocales: [&#039;es&#039;, &#039;en&#039;],
    resourceProviders: [new ArrayTranslationResourceProvider()],
);
```

A translatable exception can then be translated with `$exception-&gt;trans($translator)`. The resource provider supplies translations; the library does not create a translator automatically.

## Dependency Injection

Applications using Symfony DependencyInjection can import:

```yaml
imports:
    - { resource: &#039;../vendor/derafu/array/resources/config/array-services.yaml&#039; }
```

The recipe tags `ArrayTranslationResourceProvider` with `derafu_translation.resource_provider`. Pass providers with that tag to `TranslatorFactory::create()` through its `$resourceProviders` argument, following the setup in [Derafu Translation](https://www.derafu.dev/docs/core/translation).





---
Last updated on 15/11/2026
#php
