PHPackages                             peak/array-validation - 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. peak/array-validation

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

peak/array-validation
=====================

Validation utilities for array structure

3.2.0(6y ago)15422MITPHPPHP &gt;=7.2

Since Feb 7Pushed 6y ago1 watchersCompare

[ Source](https://github.com/peakphp/array-validation)[ Packagist](https://packagist.org/packages/peak/array-validation)[ RSS](/packages/peak-array-validation/feed)WikiDiscussions master Synced 1mo ago

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

Peak/ArrayValidation
====================

[](#peakarrayvalidation)

[![version](https://camo.githubusercontent.com/9e70afbe508c28b7594deb23340631b82817421c81df8f286d2be4510e56aaab/68747470733a2f2f706f7365722e707567782e6f72672f7065616b2f61727261792d76616c69646174696f6e2f76657273696f6e)](https://packagist.org/packages/peak/array-validation)[![Total Downloads](https://camo.githubusercontent.com/852b84da22c042eba89daf5e758d833e73d9fa253beee8c3ddbf1cf0ff5e3675/68747470733a2f2f706f7365722e707567782e6f72672f7065616b2f61727261792d76616c69646174696f6e2f646f776e6c6f616473)](https://packagist.org/packages/peak/array-validation)[![License](https://camo.githubusercontent.com/c5d5b633a52056472174410167c625cd378f131c3f4a53bafa0dd4ebad912ed2/68747470733a2f2f706f7365722e707567782e6f72672f7065616b2f61727261792d76616c69646174696f6e2f6c6963656e7365)](https://github.com/peakphp/array-validation/blob/master/LICENSE.md)

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

[](#installation)

```
 composer require peak/array-validation

```

What is this?
-------------

[](#what-is-this)

This component help you to validate array structure by:

- validating the type of any key values
- ensuring a data structure with expected keys requirements
- preventing structure pollution by allowing only a set of keys

This is especially useful when dealing with json data request, before using the data, you must validate his content so you can afterward check the value of those keys with your business logic without worrying about the type or presence of any key value.

How to use
==========

[](#how-to-use)

##### 8 Usages

[](#8-usages)

1- General validation "à la carte" (stateless)
----------------------------------------------

[](#1--general-validation-à-la-carte-stateless)

```
$validator = new Validator();

if ($validator->expectExactlyKeys($data, $keys) === true) {
    // ...
}
```

2- Validation with fluent interface (stateful)
----------------------------------------------

[](#2--validation-with-fluent-interface-stateful)

```
$data = [ // data
    'tags' => [],
    'name' => 'foobar'
];
$validation = new Validation($data);

$validation
    ->expectExactlyKeys(['tags', 'name'])
    ->expectKeyToBeArray('tags');
    ->expectKeyToBeString('name');

if ($validation->hasErrors()) {
    // $lastError = $validation->getLastError();
    // $errors = $validation->getErrors();
}
```

3- Strict validation with fluent interface (stateful)
-----------------------------------------------------

[](#3--strict-validation-with-fluent-interface-stateful)

```
$validation = new StrictValidation($data);

// will throw an exception if any of tests below fail
$validation
    ->expectOnlyKeys(['id', 'title', 'description', 'isPrivate', 'tags'])
    ->expectAtLeastKeys(['id', 'title', 'description'])
    ->expectKeyToBeInteger('id')
    ->expectKeysToBeString(['title', 'description'])
    ->expectKeyToBeBoolean('isPrivate')
    ->expectKeyToBeArray('tags');

// if we reach this point, it means the array structure is
// valid according to the validation rules above.
```

4- Create a ValidationDefinition for later usage
------------------------------------------------

[](#4--create-a-validationdefinition-for-later-usage)

```
$vDef = new ValidationDefinition();
$vDef
    ->expectOnlyKeys(['title', 'content', 'description'])
    ->expectAtLeastKeys(['title', 'content'])
    ->expectKeysToBeString(['title', 'content', 'description']);

$validation = new ValidationFromDefinition($vDef, $data);

if ($validation->hasErrors()) {
    // $validation->getErrors();
}
```

5- Create a validation Schema for later usage
---------------------------------------------

[](#5--create-a-validation-schema-for-later-usage)

Schema is just another way to write validation definitions. This format is ideal when you want to store schemas in file (ex: json, php array file, yml, etc.)

```
$mySchema = [
    'title' => [
        'type' => 'string',
        'required' => true
    ],
    'content' => [
        'type' => 'string',
        'nullable' => true,
    ],
];

$schema = new Schema(new SchemaCompiler(), $mySchema, 'mySchemaName');

$validation = new ValidationFromSchema($schema, $data);

if ($validation->hasErrors()) {
    // $validation->getErrors();
}
```

6- Strict validation using ValidationDefinition
-----------------------------------------------

[](#6--strict-validation-using-validationdefinition)

```
// all validation definitions are executed at object creation and an exception is thrown if any of tests failed
new StrictValidationFromDefinition($validationDefinition, $arrayToValidate);
```

7- Strict validation using Schema
---------------------------------

[](#7--strict-validation-using-schema)

```
// all validation definitions are executed at object creation and an exception is thrown if any of tests failed
new StrictValidationFromSchema($schema, $arrayToValidate);
```

8- Validation and Strict Validation with ValidationBuilder
----------------------------------------------------------

[](#8--validation-and-strict-validation-with-validationbuilder)

```
$validation = new ValidationBuilder();
$validation
    ->expectOnlyKeys(['title', 'content', 'description'])
    ->expectAtLeastKeys(['title', 'content'])
    ->expectKeysToBeString(['title', 'content', 'description']);

if ($validation->validate($data) === false)  {
    // $validation->getErrors();
    // $validation->getLastError();
}
```

and with strict validation:

```
//  will throw an exception if any of tests fail
$validation->strictValidate($data);
```

Validation methods
==================

[](#validation-methods)

```
interface ValidationInterface
{
    public function expectExactlyKeys(array $keys);
    public function expectOnlyOneFromKeys( array $keys);
    public function expectAtLeastKeys(array $keys);
    public function expectOnlyKeys(array $keys);
    public function expectNKeys(int $n);
    public function expectKeyToBeArray(string $key, bool $acceptNull = false);
    public function expectKeysToBeArray(array $keys, bool $acceptNull = false);
    public function expectKeyToBeInteger(string $key, bool $acceptNull = false);
    public function expectKeysToBeInteger(array $keys, bool $acceptNull = false);
    public function expectKeyToBeFloat(string $key, bool $acceptNull = false);
    public function expectKeysToBeFloat(array $keys, bool $acceptNull = false);
    public function expectKeyToBeString(string $key, bool $acceptNull = false);
    public function expectKeysToBeString(array $keys, bool $acceptNull = false);
    public function expectKeyToBeBoolean(string $key, bool $acceptNull = false);
    public function expectKeysToBeBoolean(array $keys, bool $acceptNull = false);
    public function expectKeyToBeObject(string $key, bool $acceptNull = false);
    public function expectKeysToBeObject(array $keys, bool $acceptNull = false);
}
```

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95% 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 ~9 days

Total

7

Last Release

2236d ago

Major Versions

1.1.0 → 2.0.02020-02-24

2.0.0 → 3.0.02020-03-22

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1209308?v=4)[François Lajoie](/maintainers/1franck)[@1franck](https://github.com/1franck)

---

Top Contributors

[![1franck](https://avatars.githubusercontent.com/u/1209308?v=4)](https://github.com/1franck "1franck (57 commits)")[![ordago](https://avatars.githubusercontent.com/u/6376814?v=4)](https://github.com/ordago "ordago (3 commits)")

---

Tags

arrayphpvalidationvalidationarraypeak

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/peak-array-validation/health.svg)

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

###  Alternatives

[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)[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)[league/config

Define configuration arrays with strict schemas and access values with dot notation

564302.2M24](/packages/league-config)[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k9.2M108](/packages/cuyz-valinor)[openlss/lib-array2xml

Array2XML conversion library credit to lalit.org

31052.5M47](/packages/openlss-lib-array2xml)

PHPackages © 2026

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