drgmszo076956 2014-11-21 04:03
浏览 80
已采纳

在迭代数组时使用unset()来删除空值

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条回答 默认 最新

  • dongwei1855 2014-11-21 04:06
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题