PHPackages                             modethirteen/xarray - 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. modethirteen/xarray

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

modethirteen/xarray
===================

A utility for traversing PHP arrays with an XPath-like syntax

1.2.3(5y ago)03.6k11Apache-2.0PHPPHP ^7.2.0CI failing

Since Apr 2Pushed 4y ago11 watchersCompare

[ Source](https://github.com/modethirteen/XArray)[ Packagist](https://packagist.org/packages/modethirteen/xarray)[ RSS](/packages/modethirteen-xarray/feed)WikiDiscussions main Synced today

READMEChangelog (7)Dependencies (3)Versions (8)Used By (1)

❎ Array
=======

[](#-array)

A utility for traversing PHP arrays with an XPath-like syntax.

[![github.com](https://github.com/modethirteen/XArray/workflows/build/badge.svg)](https://github.com/modethirteen/XArray/actions?query=workflow%3Abuild)[![codecov.io](https://camo.githubusercontent.com/368e6337228cda75fa235048f14d993276840c4bba095d4d5683e6b16564394a/68747470733a2f2f636f6465636f762e696f2f6769746875622f6d6f6465746869727465656e2f5841727261792f636f7665726167652e7376673f6272616e63683d6d61696e)](https://codecov.io/github/modethirteen/XArray?branch=main)[![Latest Stable Version](https://camo.githubusercontent.com/c09893eb02b142ac8cbd2e33e7ced6a7f352841f4d1fef0cd5d841f49f537cf6/68747470733a2f2f706f7365722e707567782e6f72672f6d6f6465746869727465656e2f7861727261792f76657273696f6e2e737667)](https://packagist.org/packages/modethirteen/xarray)[![Latest Unstable Version](https://camo.githubusercontent.com/2d52b24f85ce8e03e9274ba7f3c58d5c36d9af35344b63629fce798b9bb9651c/68747470733a2f2f706f7365722e707567782e6f72672f6d6f6465746869727465656e2f7861727261792f762f756e737461626c65)](https://packagist.org/packages/modethirteen/xarray)

Requirements
------------

[](#requirements)

- PHP 7.4 (main, 2.x)

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

[](#installation)

Use [Composer](https://getcomposer.org/). There are two ways to add XArray to your project.

From the composer CLI:

```
./composer.phar require modethirteen/xarray
```

Or add modethirteen/xarray to your project's composer.json:

```
{
    "require": {
        "modethirteen/xarray": "dev-main"
    }
}
```

`dev-main` is the main development branch. If you are using XArray in a production environment, it is advised that you use a stable release.

Assuming you have setup Composer's autoloader, XArray can be found in the `modethirteen\XArray\` namespace.

Types
-----

[](#types)

### XArray

[](#xarray)

```
// use XArray from scratch
$x1 = new XArray();

// set some values
$x1->setVal('foo/bar', 'baz');
$x1->setVal('qux', ['fred', 'quxx']);

// get some values
$result = $x1->getVal('foo/bar'); // 'baz'
$result = $x1->getVal('qux'); // ['fred', 'quxx']

// which key paths have been defined in the XArray?
$keys = $x1->getKeys(); // ['foo', 'foo/bar', 'qux']

// reduce output to the key paths that have values
$flattened = $x1->toFlattenedArray(); // ['foo/bar' => 'baz', 'qux' => ['fred', 'quxx']]

// get the array (the underlying array data structure)
$array1 = $x1->toArray();

// create a new XArray from the existing array
$x2 = new XArray($array1);

// override a value and set a new value
$x2->setVal('foo/bar', ['qux', 'baz']);
$x2->setVal('bar', 'foo');

// get some values
$result = $x2->getVal('foo/bar'); // ['qux', 'baz']
$result = $x2->getVal('bar'); // 'foo'

// we can get a value strictly as a string, if we are in strict typing mode!
// first we set some non-string values...
$x2->setVal('qwerty', true);
$x2->setVal('asdf', new class {
    public function __toString() : string {
        return 'zxcv';
    }
});

// ...and cast them to string!
$result = $x2->getString('qwerty'); // 'true'
$result = $x2->getString('asdf'); // 'zxcv'

// of course, string values themselves can be fetched as strict string types
$result = $x2->getString('foo/bar'); // 'qux'

// get the new array
$array2 = $x2->toArray();

// XArray does not mutate the source array
assert($array1 !== $array2);
```

### MutableXArray (extends XArray)

[](#mutablexarray-extends-xarray)

```
// MutableXArray always requires a source array
$array1 = [
  'foo' => [
      'bar',
      'baz'
  ]
];
$x = new MutableXArray($array1);

// set some values
$x->setVal('foo/bar', 'qux');
$x->setVal('fred', 'quxx');

// get the new array
$array2 = $x->toArray();

// MutableXArray mutates the source array
assert($array1 === $array2);
```

### SchemaLockedArray (extends XArray)

[](#schemalockedarray-extends-xarray)

```
// SchemaLockedArray will block the setting of any values if the key path is not allowlisted in a schema
$x = new SchemaLockedArray(new SchemaBuilder());

// throws SchemaLockedArrayUndefinedKeyException
$x->setVal('foo', 'bar');

// a schema can be built with a fluent API
$schemaBuilder = (new SchemaBuilder())
    ->with('foo')

    // also allowlists bar
    ->with('bar/baz')

    // also allowlists plugh and plugh/xyzzy
    ->with('plugh/xyzzy/fred');

// a schema can also be inferred from another XArray by analyzing the array's defined key paths
$x = new XArray([
    'foo' => 'qux',
    'bar' => [
        'baz' => true
    ],
    'plugh' => [
        'xyzzy' => [
            'fred' => [
                'sodium',
                'iodine'
            ]
        ]
    ]
]);
$schemaBuilder = SchemaBuilder::newFromXArray($x);

// either way, the SchemaLockedArray will only ever contain the key paths that are defined in the schema
$x = new SchemaLockedArray($schemaBuilder);
```

Serialization
-------------

[](#serialization)

### JSON

[](#json)

```
// An XArray (or any derived instance) can have a specialized serializer attached, such as JSON...
$x = (new XArray([
    'foo' => [
        'bar' => [
            "//baz",
            'qux'
        ]
    ],
    'plugh' => 'xyzzy'
]))->withSerializer(
    (new JsonSerializer())
        ->withUnescapedSlashes()
        ->withPrettyPrint()
);

// the serializer is engaged when writing the array into a textual representation
echo $x->toString();
echo strval($x);
```

```
{
    "foo": {
        "bar": [
            "//baz",
            "qux"
        ]
    },
    "plugh": "xyzzy"
}
```

### XML

[](#xml)

```
// XML has the option to wrap the output in a root element to ensure valid XML schema
$x = (new XArray([
    'foo' => [
        'bar' => [
            'qux',
            'baz'
        ]
    ],
    'qux' => [
        'fred',
        'quxxx'
    ],
    'bar' => 'foo',
    'querty' => true,
    'asdf' => 'zxcv'
]))->withSerializer(
    (new XmlSerializer())
        ->withRootElement('xyzzy')
);
echo $x->toString();
```

```

    qux
    baz

  fred
  quxxx
  foo
  true
  zxcv

```

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~288 days

Recently: every ~176 days

Total

7

Last Release

2013d ago

Major Versions

0.1.1 → 1.0.02019-01-22

PHP version history (3 changes)0.1.0PHP &gt;=5.4.0

1.0.0PHP &gt;=7.2.0

1.2.3PHP ^7.2.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/45862?v=4)[James Andrew Vaughn](/maintainers/modethirteen)[@modethirteen](https://github.com/modethirteen)

---

Top Contributors

[![modethirteen](https://avatars.githubusercontent.com/u/45862?v=4)](https://github.com/modethirteen "modethirteen (51 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/modethirteen-xarray/health.svg)

```
[![Health](https://phpackages.com/badges/modethirteen-xarray/health.svg)](https://phpackages.com/packages/modethirteen-xarray)
```

PHPackages © 2026

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