vicky793
vicky793

Reputation: 521

how to check and remove completely null value array from multidimensional array?

I have multidimensional array. I want to remove arrya if array all values are null. I have the following array:

"qualifications" => array(
[0] => array(
  "qualifications" => "demo"
  "acquisition_date" => null
),
[1] => array(
  "qualifications" => null
  "acquisition_date" => null
),
[2] => array(
  "qualifications" => "test"
  "acquisition" => 123
)
);

I want to remove array like index[1]. I'm trying to the following code:

$educationalEmptyArray = 'false';
    if (!array_filter(array_map('array_filter', $educational))) {
        $educationalEmptyArray = 'true';
    }

how to unset or remove completely null value array like index[1] array.

Upvotes: 0

Views: 58

Answers (2)

Vishnu Vijaykumar
Vishnu Vijaykumar

Reputation: 450

This is not exactly the right way to do, but still works:

   $input = array(
        '0' => array(
        "qualifications" => "demo",
        "acquisition_date" => null
        ),
        '1' => array(
        "qualifications" => null,
        "acquisition_date" => null
        ),
        '2' => array(
        "qualifications" => "test",
        "acquisition" => 123
        )
    );
    $output = array();
    foreach($input as $array) {
        foreach($array as $key=>$value){
            if($array[$key]){
                array_push($output,$array);
                break;
            }
        }
    }

The $output array completely removes null value array like index[1] array. The above code gives the below output:

Array
(
    [0] => Array
        (
            [qualifications] => demo
            [acquisition_date] => 
        )

    [1] => Array
        (
            [qualifications] => test
            [acquisition] => 123
        )

)

Upvotes: 1

Spholt
Spholt

Reputation: 4012

I would suggest leveraging Laravel Collections for this as it makes this sort of manipulation easier. There are many, many, many ways to do this but this should do the trick

$collection = collect($educational)->reject(function ($items) {
    foreach ($items as $item) {
        if ($item !== null) {
            // We have an actual value so we can safely ignore and return early
            return false;
        }
    }
    // We didn't find a non-null value, so we reject this array
    return true;
});

I'm not sure how eficient this will be off the top of my head

Upvotes: 0

Related Questions