Home > Software design >  How to delete an empty array in php
How to delete an empty array in php

Time:12-15

I am dealing with arrays in php. And have an empty array problem like below:

In Controller :

        $name = [];
        if (!empty($request->mobile)) { 
            $name['mobile'] = $request->mobile;
        }
        dd($name);

        //Result :

        array(1) {
            ["mobile"]=>
            array(2) {
              [0]=>
              array(2) {
                ["link"]=>
                string(4) "adc.co"
                ["image"]=>
                string(36) "a1119e740c170e5a29bf2fd4deff8c83.png"
              }
              [1]=>
              array(0) {
              }
            }
          }

Is there a way for me to remove the empty array inside $name . I want to clear this array:

[1]=>
   array(0) {
   }

Thanks

CodePudding user response:

you can use PHP array_filter to remove any empty values like null, 0, ''

print_r(array_filter($name));

or

you can use laravel helper as you have not mentioned the laravel version hope you're using the latest one(8.x).

use Illuminate\Support\Arr;

$filtered = Arr::where($name, function ($value, $key) {
    return !empty($value);
});
  • Related