PHPackages                             selfphp/php-typecheck - 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. selfphp/php-typecheck

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

selfphp/php-typecheck
=====================

Runtime type validation for arrays and structured data. in PHP

v1.1.0(1y ago)02MITPHPPHP ^8.1

Since May 27Pushed 1y agoCompare

[ Source](https://github.com/selfphp/php-typecheck)[ Packagist](https://packagist.org/packages/selfphp/php-typecheck)[ RSS](/packages/selfphp-php-typecheck/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (1)Versions (4)Used By (0)

PhpTypeCheck
============

[](#phptypecheck)

**PhpTypeCheck** is a lightweight PHP library for validating runtime types in arrays and nested data structures.
It helps ensure that incoming data (e.g., from APIs, forms, or dynamic sources) matches expected scalar or object types.

---

🚀 Features
----------

[](#-features)

- ✅ Validate array elements against scalar or object types
- 🔁 Support for recursive (nested) arrays
- 🧩 Validate associative structures with `assertStructure()`
- 🔍 Optional keys with `key?` syntax
- 🧠 Descriptive error messages with full path and actual/expected types
- 🧾 Soft validation via `checkArrayOfType()` and `checkStructure()`
- 🧪 Type inspection via `describeType()`
- 📤 Structured error output with `TypeCheckException::toArray()`
- 🧪 Fully tested with PHPUnit
- 🎯 Framework-agnostic (works in Symfony, Laravel, Slim, or plain PHP)

---

📦 Installation
--------------

[](#-installation)

```
composer require selfphp/php-typecheck
```

---

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

[](#requirements)

- PHP &gt;= 8.1
- Composer

This library uses modern PHP 8.1 features like `readonly` properties.

---

✨ Basic Usage
-------------

[](#-basic-usage)

### Validate flat arrays

[](#validate-flat-arrays)

```
use Selfphp\PhpTypeCheck\TypeChecker;

TypeChecker::assertArrayOfType([1, 2, 3], 'int');       // ✅ OK
TypeChecker::assertArrayOfType(['a', 'b'], 'string');   // ✅ OK
```

### Validate arrays of objects

[](#validate-arrays-of-objects)

```
TypeChecker::assertArrayOfType([new User(), new User()], User::class); // ✅ OK
```

### Recursive validation

[](#recursive-validation)

```
$data = [[1, 2], [3, 4]];
TypeChecker::assertArrayOfType($data, 'int', true); // ✅ OK
```

### Fails with meaningful error

[](#fails-with-meaningful-error)

```
TypeChecker::assertArrayOfType([1, 'two', 3], 'int');
// ❌ Throws TypeCheckException: Element at [1] is of type string, expected int
```

---

✅ Soft validation (no exceptions)
---------------------------------

[](#-soft-validation-no-exceptions)

### `checkArrayOfType()`

[](#checkarrayoftype)

```
if (!TypeChecker::checkArrayOfType([1, 'two'], 'int')) {
    echo "Invalid array values!";
}
```

### `checkStructure()`

[](#checkstructure)

```
$data = ['email' => 'test@example.com'];
$schema = ['email' => 'string', 'phone?' => 'string'];

if (!TypeChecker::checkStructure($data, $schema)) {
    echo "Invalid structure!";
}
```

---

🧩 Validate structured arrays
----------------------------

[](#-validate-structured-arrays)

```
TypeChecker::assertStructure(
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'string', 'age' => 'int']
);

// with nested structures and optional keys
TypeChecker::assertStructure(
    ['profile' => ['city' => 'Berlin'], 'email' => 'a@example.com'],
    ['profile' => ['city' => 'string'], 'email?' => 'string']
);
```

---

📤 Structured error reporting
----------------------------

[](#-structured-error-reporting)

If a `TypeCheckException` is thrown, you can convert it to a machine-readable format:

```
try {
    TypeChecker::assertArrayOfType([1, 'x'], 'int');
} catch (TypeCheckException $e) {
    echo json_encode($e->toArray(), JSON_PRETTY_PRINT);
}
```

```
{
  "message": "Element at [1] is of type string, expected int",
  "path": "1",
  "expected": "int",
  "actual": "string"
}
```

---

🧪 Describe value types
----------------------

[](#-describe-value-types)

```
TypeChecker::describeType(42);                         // int
TypeChecker::describeType(['a', 'b']);                 // array
TypeChecker::describeType([1, 'x']);                   // array
TypeChecker::describeType([new User(), new User()]);  // array
```

---

🛠 Roadmap
---------

[](#-roadmap)

- `assertStructure(array $data, array $schema)` for complex key/type validation
- `checkArrayOfType()` and `checkStructure()` for soft validation
- Structured error reporting via `toArray()`
- Type parser support for `array`
- Optional integration with static analysis tools (Psalm, PHPStan)

---

📄 License
---------

[](#-license)

MIT ©2025 [SELFPHP](https://github.com/selfphp)

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance46

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.9% 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 ~0 days

Total

3

Last Release

401d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d9da560cb003f45736b988e005afce3c17647553a1c1cea771b3cde3b7890ad1?d=identicon)[SELFPHP](/maintainers/SELFPHP)

---

Top Contributors

[![DamirEnseleit](https://avatars.githubusercontent.com/u/206047444?v=4)](https://github.com/DamirEnseleit "DamirEnseleit (8 commits)")[![selfphp](https://avatars.githubusercontent.com/u/12782362?v=4)](https://github.com/selfphp "selfphp (1 commits)")

---

Tags

validationutilityassertprimitivetype-checkingselfphptypecheck

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/selfphp-php-typecheck/health.svg)

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

###  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.1k430.4M1.7k](/packages/nette-utils)[danielstjules/stringy

A string manipulation library with multibyte support

2.4k26.3M192](/packages/danielstjules-stringy)[voku/arrayy

Array manipulation library for PHP, called Arrayy!

4915.7M18](/packages/voku-arrayy)[mage2tv/magento-cache-clean

This package has been migrated to mage-os/magento-cache-clean. Please switch over at your convenience.

5442.1M3](/packages/mage2tv-magento-cache-clean)[vaimo/composer-patches

Applies a patch from a local or remote file to any package that is part of a given composer project. Patches can be defined both on project and on package level. Optional support for patch versioning, sequencing, custom patch applier configuration and patch command for testing/troubleshooting added patches.

3014.6M26](/packages/vaimo-composer-patches)[lodash-php/lodash-php

A port of Lodash to PHP

528756.5k5](/packages/lodash-php-lodash-php)

PHPackages © 2026

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