Search code examples
phparraysunset

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


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?


Solution

  • 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!