Convert Empty Data of Any Type to Null in PHP with Nullify

Convert Empty Data of Any Type to Null in PHP with Nullify cover image

Nullify is a plain PHP class to convert empty data of any type to null. PHP ^8.0 is required to use this class.

Installation

You need to install this package via composer:

composer require michael-rubel/nullify

Usage

use MichaelRubel\Nullify\Nullify;

Nullify::the($value);

Note: the class checks also nested iterables and ArrayAccess objects.

Examples

$value = null;
Nullify::the($value); // null

$value = '';
Nullify::the($value); // null

$value = [];
Nullify::the($value); // null

$value = (object) [];
Nullify::the($value); // null

$value = new \stdClass;
Nullify::the($value); // null

Check nested elements:

$values = new Collection([
    'valid'        => true,
    'empty_array'  => [],
    'empty_string' => '',
    'collection'   => new Collection([
        'invalid' => new \stdClass,
    ])
]);

Nullify::the($values);

// Illuminate\Support\Collection^ {#459
//   #items: array:4 [
//     "valid" => true
//     "empty_array" => null
//     "empty_string" => null
//     "collection" => Illuminate\Support\Collection^ {#461
//       #items: array:1 [
//         "invalid" => null
//       ]
//       #escapeWhenCastingToString: false
//     }
//   ]
//   #escapeWhenCastingToString: false
// }

If you use Laravel Collections, you can make a macro:

Collection::macro('nullify', function () {
    return $this->map(fn ($value) => Nullify::the($value));
});

collect(['', [], (object) [], new \stdClass, '✔'])
    ->nullify()
    ->toArray(); // [0 => null, 1 => null, 2 => null, 3 => null, 4 => '✔']

For more details and source code you can visit this package’s documentation on Github.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a free call with CodeBrisk Open in new tab