PHPackages                             snipershady/typeidentifier - 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. snipershady/typeidentifier

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

snipershady/typeidentifier
==========================

Free service to identify primitive type of a variable

v1.0.10(1mo ago)33.6k↓100%11GPL-2.0-onlyPHPPHP &gt;=5.6CI passing

Since Sep 26Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/snipershady/type-identifier)[ Packagist](https://packagist.org/packages/snipershady/typeidentifier)[ Docs](https://www.spinfo.it)[ RSS](/packages/snipershady-typeidentifier/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (12)Used By (1)

type-identifier
===============

[](#type-identifier)

A lightweight, robust PHP library for identifying and sanitizing primitive data types in real-world scenarios.

Perfect for normalizing values from associative arrays, superglobal arrays, HTTP requests, and any untyped data sources.

Badges
------

[](#badges)

[![Latest Version](https://camo.githubusercontent.com/6d2ad5c1605155edbd921fd7ae0c33fa82d74aa56cf4aca95c253d14a7c406cf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736e6970657273686164792f747970656964656e7469666965722e737667)](https://packagist.org/packages/snipershady/typeidentifier)[![PHP Version](https://camo.githubusercontent.com/a22171b5f165cbfddc26f508343d29437279475ee3689228e70da7ab4a5a9d16/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f736e6970657273686164792f747970656964656e7469666965722e737667)](https://www.php.net/)[![License: GPL v2](https://camo.githubusercontent.com/34fd4798bfe47593a94283d1d4fb5c522738d07b84c13f374f10485c0e0ffbbf/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d47504c76322d626c75652e737667)](./LICENSE)[![Stars](https://camo.githubusercontent.com/a4c4cfe927583040dcaa693bf3448c9cca60950fc5e851d1e0733db3d4030db3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f736e6970657273686164792f747970652d6964656e746966696572)](https://github.com/snipershady/type-identifier/stargazers)[![Issues](https://camo.githubusercontent.com/e75fef050c455d11b89c147d1917c5abbfd5451a09e268107991a1a3702ac01f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f736e6970657273686164792f747970652d6964656e746966696572)](https://github.com/snipershady/type-identifier/issues)

Why type-identifier?
--------------------

[](#why-type-identifier)

When working with HTTP requests, legacy codebases, or loosely-typed data sources, you often receive everything as strings. This library intelligently detects the actual primitive type and returns properly typed values, eliminating the need for repetitive manual casting and validation.

Features
--------

[](#features)

- ✅ **Smart type detection**: Automatically identifies `int`, `float`, `bool`, `string`, and `null`
- ✅ **Whitespace handling**: Optional trimming for clean string values
- ✅ **Type forcing**: Force values to remain as strings when needed
- ✅ **Array-safe extraction**: Safely retrieve typed values from arrays without `isset()` checks
- ✅ **Superglobal helpers**: Built-in methods for `$_GET`, `$_POST`, `$_SERVER`
- ✅ **Consistent behavior**: Works reliably across all PHP versions
- ✅ **Legacy support**: Compatible with PHP 5.6+ through PHP 8.5+
- ✅ **Zero dependencies**: Lightweight and focused

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

[](#installation)

```
composer require snipershady/type-identifier
```

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

[](#requirements)

- **PHP 5.6+** (fully compatible with PHP 8.5+)

While this library is particularly valuable for legacy PHP 5.6 projects lacking modern type systems, it remains useful in modern PHP applications for safely handling HTTP request values and heterogeneous data structures.

Quick Start
-----------

[](#quick-start)

```
use TypeIdentifier\Service\EffectivePrimitiveTypeIdentifierService;

$ept = new EffectivePrimitiveTypeIdentifierService();

// String "1" becomes int 1
$result = $ept->getTypedValue("1"); // int(1)

// String "1.5" becomes float 1.5
$result = $ept->getTypedValue("1.5"); // float(1.5)

// Non-numeric string stays string
$result = $ept->getTypedValue("hello"); // string("hello")

// Automatic whitespace trimming
$result = $ept->getTypedValue("  hello  ", true); // string("hello")
```

Usage Examples
--------------

[](#usage-examples)

### Basic Type Identification

[](#basic-type-identification)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

// Integer detection
$result = $ept->getTypedValue("1");
// Result: 1 (int)

// Float detection
$result = $ept->getTypedValue("1.1");
// Result: 1.1 (float)

// String preservation (non-numeric)
$result = $ept->getTypedValue("1.1a");
// Result: "1.1a" (string)

// Boolean values
$result = $ept->getTypedValue(true);
// Result: true (bool)

// Null handling
$result = $ept->getTypedValue(null);
// Result: null
```

### String Trimming

[](#string-trimming)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

// Trim whitespace automatically
$result = $ept->getTypedValue("  snipershady  ", true);
// Result: "snipershady" (string)

// Preserves internal spaces
$result = $ept->getTypedValue("  hello world  ", true);
// Result: "hello world" (string)
```

### Force String Type

[](#force-string-type)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

$trim = true;
$forceString = true;

// Keep as string even if numeric
$result = $ept->getTypedValue("123", $trim, $forceString);
// Result: "123" (string, not int)

// Useful for IDs, codes, or values that should stay strings
$result = $ept->getTypedValue("007", $trim, $forceString);
// Result: "007" (string)
```

Working with Arrays
-------------------

[](#working-with-arrays)

### Safe Array Value Extraction

[](#safe-array-value-extraction)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

$data = [
    "user_id" => "42",
    "username" => "  snipershady  ",
    "price" => "19.99"
];

// Valid key - returns typed value
$userId = $ept->getTypedValueFromArray("user_id", $data);
// Result: 42 (int)

// Non-existent key - returns null (no warnings/errors)
$missing = $ept->getTypedValueFromArray("invalid_key", $data);
// Result: null

// With trimming enabled
$username = $ept->getTypedValueFromArray("username", $data, true);
// Result: "snipershady" (string, trimmed)

// Float detection
$price = $ept->getTypedValueFromArray("price", $data);
// Result: 19.99 (float)
```

HTTP Request Sanitization
-------------------------

[](#http-request-sanitization)

### POST Data

[](#post-data)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

// Assuming $_POST = ["user_id" => "123", "active" => "1"]

// Retrieve and type-cast POST values
$userId = $ept->getTypedValueFromPost("user_id");
// Result: 123 (int)

// Non-existent keys return null
$missing = $ept->getTypedValueFromPost("nonexistent");
// Result: null

// With trimming
$name = $ept->getTypedValueFromPost("username", true);
// Automatically trims whitespace
```

### GET Data

[](#get-data)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

// Assuming $_GET = ["page" => "2", "sort" => "name"]

// Retrieve and type-cast GET values
$page = $ept->getTypedValueFromGet("page");
// Result: 2 (int)

$sort = $ept->getTypedValueFromGet("sort");
// Result: "name" (string)

// Missing parameter
$filter = $ept->getTypedValueFromGet("filter");
// Result: null
```

Real-World Use Cases
--------------------

[](#real-world-use-cases)

### Form Processing

[](#form-processing)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

// Process form submission with automatic type detection
$age = $ept->getTypedValueFromPost("age"); // int or null
$name = $ept->getTypedValueFromPost("name", true); // trimmed string
$price = $ept->getTypedValueFromPost("price"); // float or null
$agreed = $ept->getTypedValueFromPost("terms"); // bool or null

if ($age !== null && $age >= 18) {
    // Safe integer comparison without manual casting
}
```

### API Parameter Handling

[](#api-parameter-handling)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

// Clean API query parameters
$limit = $ept->getTypedValueFromGet("limit") ?? 10;
$offset = $ept->getTypedValueFromGet("offset") ?? 0;
$search = $ept->getTypedValueFromGet("q", true) ?? "";

// All values are properly typed for database queries
```

### Configuration Arrays

[](#configuration-arrays)

```
$ept = new EffectivePrimitiveTypeIdentifierService();

$config = [
    "max_attempts" => "3",
    "timeout" => "30.5",
    "enabled" => "true",
    "api_key" => "  abc123xyz  "
];

$maxAttempts = $ept->getTypedValueFromArray("max_attempts", $config); // int(3)
$timeout = $ept->getTypedValueFromArray("timeout", $config); // float(30.5)
$apiKey = $ept->getTypedValueFromArray("api_key", $config, true); // string("abc123xyz")
```

API Reference
-------------

[](#api-reference)

### Main Methods

[](#main-methods)

#### `getTypedValue($value, $trim = false, $forceString = false)`

[](#gettypedvaluevalue-trim--false-forcestring--false)

Identifies and returns the primitive type of a given value.

- **Parameters:**
    - `$value` (mixed): The value to type-check
    - `$trim` (bool): Whether to trim string values (default: false)
    - `$forceString` (bool): Force return as string type (default: false)
- **Returns:** Typed primitive value or null

#### `getTypedValueFromArray($key, array $array, $trim = false, $forceString = false)`

[](#gettypedvaluefromarraykey-array-array-trim--false-forcestring--false)

Safely extracts and types a value from an array.

- **Parameters:**
    - `$key` (string): Array key to retrieve
    - `$array` (array): Source array
    - `$trim` (bool): Whether to trim string values (default: false)
    - `$forceString` (bool): Force return as string type (default: false)
- **Returns:** Typed value or null if key doesn't exist

#### `getTypedValueFromPost($key, $trim = false, $forceString = false)`

[](#gettypedvaluefrompostkey-trim--false-forcestring--false)

Retrieves and types a value from `$_POST`.

- **Parameters:**
    - `$key` (string): POST parameter name
    - `$trim` (bool): Whether to trim string values (default: false)
    - `$forceString` (bool): Force return as string type (default: false)
- **Returns:** Typed value or null

#### `getTypedValueFromGet($key, $trim = false, $forceString = false)`

[](#gettypedvaluefromgetkey-trim--false-forcestring--false)

Retrieves and types a value from `$_GET`.

- **Parameters:**
    - `$key` (string): GET parameter name
    - `$trim` (bool): Whether to trim string values (default: false)
    - `$forceString` (bool): Force return as string type (default: false)
- **Returns:** Typed value or null

Testing
-------

[](#testing)

If you have a development environment set up with PHP 8.4, set the host file ‘endpoint-test’ to point to 127.0.0.1 and run

```
composer test
```

Otherwise, use the docker found in the project that sets up the environment and runs the test suite, executing

```
docker compose run --rm --remove-orphans --build do-tests && docker compose down
```

License
-------

[](#license)

This project is released under **GPLv2**. See the [LICENSE](LICENSE) file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! To contribute:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

Please ensure your code follows PSR-12 coding standards and includes appropriate tests.

Author
------

[](#author)

Created and maintained by [snipershady](https://github.com/snipershady)

Best contributor [DamImpr](https://github.com/DamImpr)

Support
-------

[](#support)

If you find this library helpful, please consider:

- ⭐ Starring the repository
- 🐛 Reporting issues
- 📖 Improving documentation
- 🔧 Contributing code

---

**Made with ❤️ for the PHP community**

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance94

Actively maintained with recent releases

Popularity26

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.6% 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 ~126 days

Recently: every ~24 days

Total

11

Last Release

58d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/160662d52c89da3351e2a94b3d354074bf30137477fc7586eeacc52e3cb44462?d=identicon)[snipershady](/maintainers/snipershady)

---

Top Contributors

[![snipershady](https://avatars.githubusercontent.com/u/20489856?v=4)](https://github.com/snipershady "snipershady (39 commits)")[![DamImpr](https://avatars.githubusercontent.com/u/26581459?v=4)](https://github.com/DamImpr "DamImpr (5 commits)")

---

Tags

typeprimitivestrict type

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/snipershady-typeidentifier/health.svg)

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

###  Alternatives

[phpoption/phpoption

Option Type for PHP

2.7k541.2M157](/packages/phpoption-phpoption)[jetbrains/phpstorm-stubs

PHP runtime &amp; extensions header files for PhpStorm

1.4k27.7M67](/packages/jetbrains-phpstorm-stubs)[marc-mabe/php-enum

Simple and fast implementation of enumerations with native PHP

49444.8M97](/packages/marc-mabe-php-enum)[symfony/type-info

Extracts PHP types information.

19751.9M114](/packages/symfony-type-info)[consistence/consistence

Consistence - consistent approach and additions to PHP's functionality

1831.1M18](/packages/consistence-consistence)[pinkary-project/type-guard

Type Guard module is part of the Pinkary Project, and allows you to \*\*narrow down the type\*\* of a variable to a more specific type.

198102.4k14](/packages/pinkary-project-type-guard)

PHPackages © 2026

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