PHPackages                             sarhan/php-flatten - 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. sarhan/php-flatten

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

sarhan/php-flatten
==================

Flattens multidimensional arrays, traversables and vars into one dimensional array.

v4.0.1(2y ago)21177.7k—1.8%51LGPL-3.0-or-laterPHPPHP ^7.1|^8.0CI failing

Since Sep 27Pushed 2y ago1 watchersCompare

[ Source](https://github.com/AlaaSarhan/php-flatten)[ Packagist](https://packagist.org/packages/sarhan/php-flatten)[ Docs](https://github.com/AlaaSarhan/php-flatten)[ RSS](/packages/sarhan-php-flatten/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (11)Used By (1)

php-flatten
===========

[](#php-flatten)

[![Latest Version](https://camo.githubusercontent.com/c6ecc81699e3ce4f89ba1441a1e1920fb5b2dc2f9746599f1864974e35f1c911/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f416c616153617268616e2f7068702d666c617474656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/AlaaSarhan/php-flatten/releases)[![Software License](https://camo.githubusercontent.com/e2a8188809c58fbefad80a34a45d9e210d93c25ea67373886c9ff6a222b07754/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4c47504c5f76332e302d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Total Downloads](https://camo.githubusercontent.com/be7656f93ab61caa9adf834829defa79298b1bc97d043487fa57f39bddb08afc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73617268616e2f7068702d666c617474656e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sarhan/php-flatten)

A utility function to mainly flatten multidimensional-arrays and traversables into a one-dimensional array, preserving keys and joining them with a customizable separator to from fully-qualified keys in the final array.

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

[](#installation)

```
  composer require sarhan/php-flatten
```

Usage
-----

[](#usage)

**Example 1**

```
use Sarhan\Flatten\Flatten;

$multiArray = [
    'say' => 'what',
    'hi' => [ 'de' => 'Hallo', 'es' => 'Hola' ]
];

/*
Flatten::__construct(
    string $separator = '.',
    string $prefix = '',
    int $flags = 0
)
*/
$flatten = new Flatten();

// Flatten::flattenToArray is provided for convinience. It internally
// calls Flatten::flatten and converts it's output, which is a 1-dimensional
// iterator, into a 1-dimensional array.
$flattened = $flatten->flattenToArray($multiArray);

// Flatten::unflattenToArray is provided for convinience. It internally
// calls Flatten::unflatten and converts it's output, which is a recursive
// generator structure, into a multi-dimensional array.
$unflattened = $flatten->unflattenToArray($flattened);

assert($flattened == [
    'say' => what
    'hi.de' => Hallo
    'hi.es' => Hola
]);

assert($unflattened == $multiArray);
```

**Example 2**

Custom Separator and initial prefix

```
use Sarhan\Flatten\Flatten;

$allowAccess = [
    'root' => false,
    'var' => [ 'log' => ['nginx' => true, 'apt' => false], 'www' => true ],
];

$flatten = new Flatten(
  '/',  // separator
  '/'   // prefix
);

$flattened = $flatten->flattenToArray($allowAccess);

$unflattened = $flatten->unflattenToArray($flattened);

assert($flatten == [
    '/root' => false,
    '/var/log/nginx' => true,
    '/var/log/apt' => false,
    '/var/www' => true
]);

assert($unflattened == $allowAccess);
```

**Example 3**

Notice that the prefix will not be separated in FQkeys. If it should be separated, separator must be appeneded to the prefix string.

```
use Sarhan\Flatten\Flatten;

$api = [
    'category' => [ 'health' => 321, 'sport' => 769, 'fashion' => 888 ],
    'tag' => [ 'soccer' => 7124, 'tennis' => [ 'singles' => 9833, 'doubles' => 27127 ] ],
];

$flatten = new Flatten('/', 'https://api.dummyhost.domain/');

$flattened = $flatten->flattenToArray($api);

$unflattened = $flatten->unflattenToArray($flattened);

assert($flattened == [
    'https://api.dummyhost.domain/category/health' => 321,
    'https://api.dummyhost.domain/category/sport' => 769,
    'https://api.dummyhost.domain/category/fashion' => 888,
    'https://api.dummyhost.domain/tag/soccer' => 7124,
    'https://api.dummyhost.domain/tag/tennis/singles' => 9833,
    'https://api.dummyhost.domain/tag/tennis/doubles' => 27127
]);

assert($unflattened == $api);
```

**Example 4**

Numeric keys are treated as associative keys.

**Note:** This behavior can be changed using flags. See [FLAG\_NUMERIC\_NOT\_FLATTENED](#numeric_not_flattened)

```
use Sarhan\Flatten\Flatten;

$nutrition = [
    'nutrition',
    'fruits' => [ 'oranges', 'apple', 'banana' ],
    'veggies' => ['lettuce', 'broccoli'],
];

$flatten = new Flatten('-');

$flattened = $flatten->flattenToArray($nutrition);

$unflattened = $flatten->unflattenToArray($flattened);

assert($flattened == [
    '0' => 'nutrition',
    'fruits-0' => 'oranges',
    'fruits-1' => 'apple',
    'fruits-2' => 'banana',
    'veggies-0' => 'lettuce',
    'veggies-1' => 'broccoli'
]);

assert($unflattened == $nutrition);
```

### Flags

[](#flags)

**FLAG\_NUMERIC\_NOT\_FLATTENED**

Turns off flattening values with numeric (integer) keys.

Those values will be wrapped in an array (preserving their keys) and associated to the parent FQK.

```
use Sarhan\Flatten\Flatten;

$examples = [
    'templates' => [
      ['lang' => 'js', 'template' => "console.log('%s');"],
      ['lang' => 'php', 'template' => 'echo "%s";']
    ],
    'values' => [3 => 'hello world', 5 => 'what is your name?']
];

$flatten = new Flatten(
  '.',
  'examples.',
  Flatten::FLAG_NUMERIC_NOT_FLATTENED
);

$flattened = $flatten->flattenToArray($examples);

$unflattened = $flatten->unflattenToArray($flattened);

assert($flattened == [
    'examples.templates' => [
        [
            'lang' => 'js',
            'template' => 'console.log(\'%s\')';
        ],
        [
            'lang' => 'php',
            'template' => 'echo "%s"'
        ]
    ],
    'examples.values' => [
        3 => 'hello world',
        5 => 'what is your name?'
    ]
]);

assert($unflattened == $examples);
```

Top level numeric (integer) keys will also be returned into an array assigned to the passed prefix.

```
use Sarhan\Flatten\Flatten;

$seats = [
  'A1',
  'A2',
  'B1',
  'B2',
  '_reserved' => ['A1', 'B1'],
  '_blocked' => ['B2']
];

$flatten = new Flatten(
  '_',
  'seats',
  Flatten::FLAG_NUMERIC_NOT_FLATTENED
);

$flattened = $flatten->flattenToArray($seats);

$unflattened = $flatten->unflattenToArray($flattened);

assert($flattened == [
    'seats' => ['A1', 'A2', 'B1', 'B2'],
    'seats_reserved' => ['A1', 'B1'],
    'seats_blocked' => ['B2']
]);

assert($unflattened == $seats);
```

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity42

Moderate usage in the ecosystem

Community14

Small or concentrated contributor base

Maturity74

Established project with proven stability

 Bus Factor1

Top contributor holds 98% 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 ~291 days

Recently: every ~244 days

Total

10

Last Release

897d ago

Major Versions

v1.1.1 → v2.0.02018-12-29

v2.0.0 → v3.0.02019-01-05

v3.0.0 → v4.0.02021-03-30

v1.1.2 → v3.0.12023-12-03

PHP version history (3 changes)v1.0.0PHP &gt;=5.5

v2.0.0PHP ^5.6|^7.0

v4.0.0PHP ^7.1|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/4ac822f5cc401a67c872d18e92a832d23033d22b485f7309b28ebed998dd6a5b?d=identicon)[AlaaSarhan](/maintainers/AlaaSarhan)

---

Top Contributors

[![AlaaSarhan](https://avatars.githubusercontent.com/u/1851753?v=4)](https://github.com/AlaaSarhan "AlaaSarhan (49 commits)")[![Rom-axa](https://avatars.githubusercontent.com/u/50063876?v=4)](https://github.com/Rom-axa "Rom-axa (1 commits)")

---

Tags

arraysflattenflatten-arrayphp-libraryarrayarraysflatten

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/sarhan-php-flatten/health.svg)

```
[![Health](https://phpackages.com/badges/sarhan-php-flatten/health.svg)](https://phpackages.com/packages/sarhan-php-flatten)
```

###  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)[minwork/array

Pack of advanced array functions specifically tailored for: associative (assoc) array, multidimensional array, array of objects and handling nested array elements

66256.1k5](/packages/minwork-array)[phootwork/lang

Missing PHP language constructs

1224.8M8](/packages/phootwork-lang)

PHPackages © 2026

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