PHP code example of michael-rubel / nullify

1. Go to this page and download the library: Download michael-rubel/nullify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

michael-rubel / nullify example snippets


use MichaelRubel\Nullify\Nullify;

Nullify::the($value);

$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

$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
// }

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 => '✔']