PHPackages                             seifkamal/struct-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. seifkamal/struct-array

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

seifkamal/struct-array
======================

Array structure validation

v1.1.0(6y ago)03MITPHPPHP &gt;=7.0.0

Since Apr 27Pushed 5y ago1 watchersCompare

[ Source](https://github.com/seifkamal/struct-array)[ Packagist](https://packagist.org/packages/seifkamal/struct-array)[ RSS](/packages/seifkamal-struct-array/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

[![](https://github.com/seifkamal/struct-array/workflows/Test/badge.svg)](https://github.com/seifkamal/struct-array/workflows/Test/badge.svg)

PHP Structured Arrays
=====================

[](#php-structured-arrays)

Make PHP array data validation easier and clearer by defining array structures.

Why
---

[](#why)

We often need to receive, validate, and process data objects. Sometimes, an array might be too dumb for the task at hand, requiring several unpleasant control structures to validate and setup. Moreover, creating a dedicated DTO class (or more) might be overkill, requiring a lot of boilerplate code, whilst making things like error messaging and future refactoring more difficult.

In cases like this I find myself itching for a Go/Rust like `struct` instead.

See [doc](docs/use-case.md) for a more in depth discussion.

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

[](#installation)

```
composer require seifkamal/struct-array
```

Usage
-----

[](#usage)

To define and validate an array data structure, first create a `Struct` - this requires a `name`, used for error messaging, and an `interface` - then use the provided `Validator`function to validate the data against the defined `Struct`.

A `Struct`'s `interface` ia an array consisting of string keys (matching the expected property names) and callable values. These values can be any callable PHP entity, and is expected to accept a single mixed type `$value`, and return a `bool`. Some valid examples are:

- `is_*` [variable handling functions](https://www.php.net/manual/en/ref.var.php) (`is_string`, `is_int`, `is_callable` etc.)
- A `Closure` (`function ($value): bool {}`)
- A class with an `__invoke($value): bool` method

### Example

[](#example)

Here's an example written using the provided convenient helper functions:

```
