dousenjue3214 2018-02-14 22:02
浏览 83

在数组中使用unset()函数来删除元素

Trying to delete all elements in the array (given below) which are less then 0 using the following code:

 <?php 
       $arr=array(1,2,3,4,5,-6,-7,-8,-9,-10);

        for ($i=0;$i<count($arr);$i++){
                if ($arr[$i]<0) {
                unset($arr[$i]);
                }
        }

    var_dump($arr);

    echo '<pre>', print_r($arr), '</pre>';

    ?>

However, the result is the following:

array(7) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [8]=> int(-9) [9]=> int(-10) }
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [8] => -9
    [9] => -10
)
1

Quite confused why not all the elements which are less then 0 are removed from the array. Any thoughts on this?

  • 写回答

6条回答 默认 最新

  • douhui9631 2018-02-14 22:04
    关注

    You could do this using array_filter(). The second parameter is an anonymous function that takes as argument an element of the array. Inside, you have to determine weither it should be kept or not.

    $arr=array(1,2,3,4,5,-6,-7,-8,-9,-10);
    $arr = array_filter($arr, function($e) {
        return $e >= 0 ; // keep only element greater than zero
    });
    echo '<pre>', print_r($arr), '</pre>';
    

    Outputs :

    array(5) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
      [3]=>
      int(4)
      [4]=>
      int(5)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程