Blog Detail

08

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

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

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.

Published at : 08-12-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project