amM
amM

Reputation: 529

Removing null or blank values of array

I have an array, I just print it as-
print_r($data);
It shows output as-

Array
(
    [0] => Array
        (
            [0] => Title
            [1] => Featured Image
            [2] => Catagories
            [3] => Tags
            [4] => Content
        )

    [1] => Array
        (
            [0] => title 1
            [1] => img1.jpg
            [2] => cat 1
            [3] => tag 1
            [4] => post 1 content
        )

    [2] => Array
        (
            [0] => title 2
            [1] => img2.jpg
            [2] => cat2
            [3] => tag 2
            [4] => post 2 content
        )

    [3] => Array
        (
            [0] => title 3
            [1] => img3.jpg
            [2] => cat3
            [3] => tag3
            [4] => post 3 content
        )

    [4] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
        )

    [5] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
        )

    [6] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
        )

)  

I just want to remove blank or null values from array.
I tried array_dif() and array_filter() but still I couldn't remove null values.
How is this possible?
Thanks.

Upvotes: 0

Views: 684

Answers (2)

ezakto
ezakto

Reputation: 3194

You should use array_filter with a function that also runs array_filters against the subarrays and returns false if the filtered subarrays become empty.

<?php

$array = Array(
    Array(1, 2, 3),
    Array(null, null, null),
    Array(false, false, false),
    Array(3, 2, 1)
);

$filtered = array_filter($array, function($elem) {
    return count(array_filter($elem));
});

print_r($filtered);

?>

Upvotes: 1

Brogan
Brogan

Reputation: 748

You can loop through the array, look for empty variables and use unset to remove them.


This code will loop through and check if the length of the first value in each array is at least one character long and unset it if its not.

<?php
foreach($data as $key => $value) {
    if(!isset($value[0][0]))
        unset($data[$key]);
}

This code will loop through the array in a similar way, except to check every value of every array to determine if its parrent array should be kept or left to be unset.

<?php
foreach($data as $key => $values) {
    foreach($values as $value) {
        if(isset($value[0]))
            continue 2;
    }
    unset($data[$key]);
}

Upvotes: 1

Related Questions