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] => 
        )

)
Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34
Cesar Mtz
  • 322
  • 2
  • 13

3 Answers3

1
foreach ($array as $key=>$value) {
  if ($value == '') { unset($array[$key]); }
}

That should do it.

CollinD
  • 7,304
  • 2
  • 22
  • 45
0

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;
}
curtis1000
  • 106
  • 6
  • 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 ) ) – Cesar Mtz Sep 05 '15 at 21:32
  • I just updated my solution. You would wrap the array_filter call with array_values. – curtis1000 Sep 05 '15 at 21:36
  • Thanks so much man!! it did worked! – Cesar Mtz Sep 05 '15 at 21:39
  • 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 – Cesar Mtz Sep 20 '15 at 17:42
  • 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). – curtis1000 Sep 21 '15 at 16:03
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
)
tmarois
  • 2,424
  • 2
  • 31
  • 43
  • i have tried with this one an it didn't work for me – Cesar Mtz Sep 05 '15 at 21:28
  • 1
    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. – tmarois Sep 05 '15 at 21:36