Using unset() while iterating over array to remove empty values

1.8k Views Asked by At

Trying to remove empty values from array like this. It does miss one key each time i use unset(). I know there might be better way to complete task, but i need to know why current code is one missing some keys?

$values_arr = array(
   0 => "Text",
   1 => "",
   2 => "",
   3 => "Text",
   4 => "",
   5 => "Text"
);

Works in theory

for ($i = 0; $i < count($values_arr); $i++) {
    if ( empty($values_arr[$i]) ) {
        echo "<br> Blank key found " . $i . ", value was >" . $values_arr[$i] . "<";
        //Unset commented out
        //unset($values_arr[$i]);
    }
}

var_dump($values_arr);

Output

Blank key found 1, value was ><
Blank key found 2, value was ><
Blank key found 4, value was ><

array (size=6)
  0 => string 'Text' (length=4)
  1 => string '' (length=0)
  2 => string '' (length=0)
  3 => string 'Text' (length=4)
  4 => string '' (length=0)
  5 => string 'Text' (length=4)

Unset not working

for ($i = 0; $i < count($values_arr); $i++) {
    if ( empty($values_arr[$i]) ) {
        echo "<br> Blank key found " . $i . ", value was >" . $values_arr[$i] . "<";
        unset($values_arr[$i]);
    }
}

var_dump($values_arr);

Output

Blank key found 1, value was ><
Blank key found 2, value was ><

array (size=4)
  0 => string 'Text' (length=4)
  3 => string 'Text' (length=4)
  4 => string '' (length=0)
  5 => string 'Text' (length=4)

Why key 4 is not unset?

2

There are 2 best solutions below

3
On BEST ANSWER

This should work for you:

<?php

    $values_arr = array(
                   0 => "Text",
                   1 => "",
                   2 => "",
                   3 => "Text",
                   4 => "",
                   5 => "Text"
                );

    foreach($values_arr as $k => $v) {

        if(empty($v) || $v == "")
            unset($values_arr[$k]);

    }

    print_r($values_arr);

?>

Output:

Array ( [0] => Text [3] => Text [5] => Text )


Why is your version not working?

Because in your for loop you have the condition: $i < count($values_arr)

So every iteration of the for loop it's going to check the condition! So if you unset a value in the array the count get's smaller! And after 2 unset's the for loop doesn't reach index 4 anymore!

0
On

The problem with your code is that by the time you hit index 4 it will be equal to the size of your array and the loop stops.

There's a one-liner solution to this:

$values_arr = array_filter($values_arr, 'strlen');

It performs strlen() on each array element and returns a new array with elements that are not empty strings.

Another way is to find the keys corresponding to empty string values and then unset() those keys one by one in the main array:

foreach (array_keys($values_arr, '', true) as $key) {
    unset($values_arr[$key]);
}