PHPackages                             jrfnl/php-cast-to-type - 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. jrfnl/php-cast-to-type

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

jrfnl/php-cast-to-type
======================

PHP Class to consistently cast variables to a specific type.

2.1.0(3y ago)13251.5k↓47%14GPL-2.0-or-laterPHPPHP &gt;=5.0CI passing

Since Jun 18Pushed 2mo ago3 watchersCompare

[ Source](https://github.com/jrfnl/PHP-cast-to-type)[ Packagist](https://packagist.org/packages/jrfnl/php-cast-to-type)[ Docs](https://github.com/jrfnl/PHP-cast-to-type)[ RSS](/packages/jrfnl-php-cast-to-type/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (6)Versions (6)Used By (4)

[![GitHub license](https://camo.githubusercontent.com/99d280c5a1f6abf3596fc7a96de71d3ae1003f7e99ee55140aae35bb88ba705e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d47504c76322d626c75652e737667)](https://raw.githubusercontent.com/jrfnl/PHP-cast-to-type/main/LICENSE.md)[![CS](https://github.com/jrfnl/PHP-cast-to-type/actions/workflows/cs.yml/badge.svg)](https://github.com/jrfnl/PHP-cast-to-type/actions/workflows/cs.yml)[![Lint](https://github.com/jrfnl/PHP-cast-to-type/actions/workflows/lint.yml/badge.svg)](https://github.com/jrfnl/PHP-cast-to-type/actions/workflows/lint.yml)

PHP-cast-to-type
================

[](#php-cast-to-type)

PHP Class to consistently cast variables to a specific type.

Returns either the value in the specified type or `null`.

### Features:

[](#features)

- Consistent results across PHP versions.
- Compatible with PHP4, PHP5 and PHP7 which makes it extra useful if you're coding for open source software where you don't know the library user's PHP version and the `filter_var()` functions may not be available.
- Optionally recursively cast all values in an array to the choosen type (similar to `filter_var_array()` behaviour).
- Optionally allow/disallow empty strings/arrays.
- Will succesfully cast any of the following string values to their boolean counterpart (similar to `filter_var()` behaviour, but less case-sensitive).
    - True: `'1', 'true', 'True', 'TRUE', 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON'`.
    - False: `'0', 'false', 'False', 'FALSE', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'`.
- Support for casting of `SplType` objects.

### Some Usage examples:

[](#some-usage-examples)

```
$value = 'example';
$value = CastToType::_bool( $value ); // null

$value = 'true';
$value = CastToType::_bool( $value ); // true

$value = '123';
$value = CastToType::_int( $value ); // 123

$value = array( '123' );
$value = CastToType::_int( $value ); // null
$value = CastToType::_int( $value, $array2null = false ); // array( 123 )
```

### Available methods:

[](#available-methods)

All methods are static.

- `CastToType::cast( $value, $type, $array2null = true, $allow_empty = true, $implode_array = false );`
- `CastToType::_bool( $value, $array2null = true, $allow_empty = true );`
- `CastToType::_int( $value, $array2null = true, $allow_empty = true );`
- `CastToType::_float( $value, $array2null = true, $allow_empty = true );`
- `CastToType::_string( $value, $array2null = true, $allow_empty = true );`
- `CastToType::_array( $value, $allow_empty = true );`
- `CastToType::_object( $value, $allow_empty = true );`
- `CastToType::_null( $value );`

#### Parameters:

[](#parameters)

ParamTypeDescription`$value`mixedValue to cast.`$type`stringType to cast to. Valid values: `'bool'`, `'boolean'`, `'int'`, `'integer'`, `'float'`, `'double'`, `'num'`, `'string'`, `'array'`, `'object'`.`$array2null`boolOptional. Whether to return `null` for arrays when casting to bool, int, float, num or string. If false, the individual values held in the array will recursively be cast to the specified type. Defaults to `true`.`$allow_empty`boolOptional. Whether to allow empty strings, empty arrays, empty objects. If false, `null` will be returned instead of the empty string/array/object. Defaults to `true`.### Installation

[](#installation)

#### Requirements

[](#requirements)

This package requires the PHP native [`ctype`](https://www.php.net/book.ctype) extension.

#### Stand-alone

[](#stand-alone)

1. Head to the [Releases](https://github.com/jrfnl/PHP-cast-to-type/releases) page and download the latest release zip.
2. Extract the files and place them somewhere in your project hierarchy.
3. Require the class loader using `require_once '/path/to/cast-to-type.php';`.

#### Composer

[](#composer)

If you are using PHP5+ (as you should), PHP-Cast-to\_Type is also available as a [package](https://packagist.org/packages/jrfnl/PHP-cast-to-type) installable via Composer:

```
composer require jrfnl/PHP-cast-to-type
```

### Changelog:

[](#changelog)

#### 2.1.0 (Nov 2022)

[](#210-nov-2022)

- Allow for `double` as an alias for `float` in the `CastToType::cast()` method. Thanks [@nsrosenqvist](https://github.com/nsrosenqvist) for the contribution.
- Bug fix: string `ON` not recognized as truthy when casting to boolean.
- The requirement for the `ctype` extension has been made explicit.
- The primary branch has been renamed from `master` to `main`.
- General housekeeping.

#### 2.0.1 (Jan 2018)

[](#201-jan-2018)

- Bugfix for PHP cross-version compatibility. This affected use of this class on PHP &lt; 5.2.7.
- General housekeeping.

#### 2.0 (Jun 2015)

[](#20-jun-2015)

- Updated the object casting to be in line with the way this is done in PHP7 for cross-version compatibility. Previously arrays with numerical keys cast to objects would be added to the object as a property called `array` with the value being the complete array. Now - as in PHP7 - each numerical array key will be cast to an individual property. This breaks backward-compatibility with v1.0 for array to object cast results, so please review your code if you relied on the old behaviour.
- Fixed a bug in the object casting which would return `null` for non-objects cast to objects in PHP &lt;= 5.1.
- Fixed a bug in the object casting where an empty string would not return `null` while `$allow_empty` was set to `false`.

#### 1.0 (2006 / Sept 2013)

[](#10-2006--sept-2013)

- Initial release.

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance58

Moderate activity, may be stable

Popularity40

Moderate usage in the ecosystem

Community18

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 95.8% 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 ~1353 days

Total

3

Last Release

1282d ago

### Community

Maintainers

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

---

Top Contributors

[![jrfnl](https://avatars.githubusercontent.com/u/663378?v=4)](https://github.com/jrfnl "jrfnl (137 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (5 commits)")[![nsrosenqvist](https://avatars.githubusercontent.com/u/1303475?v=4)](https://github.com/nsrosenqvist "nsrosenqvist (1 commits)")

---

Tags

type-castingtype jugglingcross version

###  Code Quality

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/jrfnl-php-cast-to-type/health.svg)

```
[![Health](https://phpackages.com/badges/jrfnl-php-cast-to-type/health.svg)](https://phpackages.com/packages/jrfnl-php-cast-to-type)
```

###  Alternatives

[sfolador/measures-for-laravel

A collection of unit conversions utils for Laravel

104.5k](/packages/sfolador-measures-for-laravel)

PHPackages © 2026

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