1

I have this array, and I want go get rid of those indexes that have no value in them, so for example in the index[0] I want to get rid of the [0] and [4] so I would have a 3 value array and so on...

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

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

    [2] => Array
        (
            [0] => 
            [1] => 11
            [2] => 12
            [3] => 
        )

)
2
  • 1
    Maybe array_filter? Commented Sep 5, 2015 at 21:00
  • Also, do you want to preserve the keys, or shift them? That is to say, should element[0][1] be 1 or 2 after the operation? Commented Sep 5, 2015 at 21:02

3 Answers 3

1

This is a good use case for array_filter. Checking for !empty() allows you to remove both empty strings and null values.

$filter_func = function($input) {
    $output = [];
    foreach ($input as $set) {
        $output[] = array_values(
            array_filter($set, function($element) {
                return !empty($element);
            })
        );
    }
    return $output;
}
Sign up to request clarification or add additional context in comments.

5 Comments

it worked but how could i set the inner values as [0] or [1] instead of the values of the previous array? Array ( [0] => Array ( [2] => 7 [4] => 8 ) [1] => Array ( [2] => 9 [3] => 10 ) [2] => Array ( [1] => 11 [2] => 12 ) )
I just updated my solution. You would wrap the array_filter call with array_values.
Thanks so much man!! it did worked!
this is removing 0s in my array is there a way to avoid that? [0] => Array ( [0] => 0 [1] => 0 [2] => 7 [3] => 0 [4] => 8 [5] => 0 ) @curtis1000
It's hard for me to know what the best filter is without knowing the range of possibilities that you want to accept. If you are always dealing with integers, you could replace the "!empty" with "is_int" to only accept integers (including zeros).
1
foreach ($array as $key=>$value) {
  if ($value == '') { unset($array[$key]); }
}

That should do it.

Comments

0

You can use array_filter()

$my_array = array_filter($my_array);

If you need to "re-index" after, you can run $my_array = array_values($my_array)

Example:

$a   = array();
$a[] = '';
$a[] = 1;
$a[] = null;
$a[] = 2;
$a[] = 3;

$a = array_filter($a);
print_r($a);

Output:

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

2 Comments

i have tried with this one an it didn't work for me
Oh. well array_filter works, but I didn't realize you are running a multidimensional array, because that won't work within the deeper array levels unless you did them manually.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.