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?