首页 文章

PHP:从数组中删除元素

提问于
浏览
2081

有没有一种简单的方法可以使用 PHP 从数组中删除元素,这样 foreach ($array) 不再包含该元素?

我认为将它设置为 null 会这样做,但显然它不起作用 .

30 回答

  • 4

    Destroy a single element of an array

    unset()

    $array1 = array('A', 'B', 'C', 'D', 'E');
    unset($array1[2]); // Delete known index(2) value from array
    var_dump($array1);
    

    输出将是:

    array(4) {
      [0]=>
      string(1) "A"
      [1]=>
      string(1) "B"
      [3]=>
      string(1) "D"
      [4]=>
      string(1) "E"
    }
    

    如果需要重新索引数组:

    $array1 = array_values($array1);
    var_dump($array1);
    

    然后输出将是:

    array(4) {
      [0]=>
      string(1) "A"
      [1]=>
      string(1) "B"
      [2]=>
      string(1) "D"
      [3]=>
      string(1) "E"
    }
    

    Pop the element off the end of array - 返回已删除元素的值

    mixed array_pop(array &$array)

    $stack = array("orange", "banana", "apple", "raspberry");
    $last_fruit = array_pop($stack);
    print_r($stack);
    print_r('Last Fruit:'.$last_fruit); // Last element of the array
    

    输出将是

    Array
    (
        [0] => orange
        [1] => banana
        [2] => apple
    )
    Last Fruit: raspberry
    

    Remove the first element (red) from an array , - 返回已删除元素的值

    mixed array_shift ( array &$array )

    $color = array("a" => "red", "b" => "green" , "c" => "blue");
    $first_color = array_shift($color);
    print_r ($color);
    print_r ('First Color: '.$first_color);
    

    输出将是:

    Array
    (
        [b] => green
        [c] => blue
    )
    First Color: red
    
  • 2367

    unset()数组中的多个碎片元素

    虽然这里已经多次提到了unset(),但是仍然需要提到unset()接受多个变量,这使得在一个操作中从数组中删除多个非连续元素变得容易:

    // Delete multiple, noncontiguous elements from an array
    $array = [ 'foo', 'bar', 'baz', 'quz' ];
    unset( $array[2], $array[3] );
    print_r($array);
    // Output: [ 'foo', 'bar' ]
    

    动态

    unset()

    unset()不接受要删除的键数组,因此下面的代码将失败(这会使得稍微更容易动态地使用unset()) .

    $array = range(0,5);
    $remove = [1,2];
    $array = unset( $remove ); // FAILS: "unexpected 'unset'"
    print_r($array);
    

    相反,unset()可以在foreach循环中动态使用:

    $array = range(0,5);
    $remove = [1,2];
    foreach ($remove as $k=>$v) {
        unset($array[$v]);
    }
    print_r($array);
    // Output: [ 0, 3, 4, 5 ]
    

    通过复制数组删除数组键

    还有另一种做法尚未提及 . 有时,摆脱某些数组键的最简单方法是简单地将$ array1复制到$ array2中 .

    $array1 = range(1,10);
    foreach ($array1 as $v) {
        // Remove all even integers from the array
        if( $v % 2 ) {
            $array2[] = $v;
        }
    }
    print_r($array2);
    // Output: [ 1, 3, 5, 7, 9 ];
    

    显然,同样的做法适用于文本字符串:

    $array1 = [ 'foo', '_bar', 'baz' ];
    foreach ($array1 as $v) {
        // Remove all strings beginning with underscore
        if( strpos($v,'_')===false ) {
            $array2[] = $v;
        }
    }
    print_r($array2);
    // Output: [ 'foo', 'baz' ]
    
  • 22

    Solutions:

    • 要删除一个元素,请使用unset( )

    unset($ array [3]);
    未设置($阵列[ '富']);

    • 要删除多个不连续的元素,也请使用unset( )

    unset($ array [3],$ array [5]);
    unset($ array ['foo'],$ array ['bar']);

    array_splice($ array,$ offset,$ length);

    Further explanation:

    使用这些函数将从PHP中删除对这些元素的所有引用 . 如果要在数组中保留一个键,但是值为空,请将空字符串分配给该元素:

    $array[3] = $array['foo'] = '';
    

    除了语法之外,使用unset( )和为元素分配''之间存在逻辑差异 . 第一个说 This doesn't exist anymore, 而第二个说 This still exists, but its value is the empty string.

    如果您正在处理数字,分配0可能是更好的选择 . 因此,如果一家公司停止 生产环境 型号XL1000链轮,它将更新其库存:

    unset($products['XL1000']);
    

    但是,如果它暂时耗尽了XL1000链轮,但计划在本周晚些时候从工厂收到新货,那么这样做会更好:

    $products['XL1000'] = 0;
    

    如果你unset( )是一个元素,PHP会调整数组,以便循环仍能正常工作 . 它没有't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here'一个例子:

    // create a "numeric" array
    $animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
    print $animals[1];  // prints 'bee'
    print $animals[2];  // prints 'cat'
    count($animals);    // returns 6
    
    // unset( )
    unset($animals[1]); // removes element $animals[1] = 'bee'
    print $animals[1];  // prints '' and throws an E_NOTICE error
    print $animals[2];  // still prints 'cat'
    count($animals);    // returns 5, even though $array[5] is 'fox'
    
    // add new element
    $animals[ ] = 'gnu'; // add new element (not Unix)
    print $animals[1];  // prints '', still empty
    print $animals[6];  // prints 'gnu', this is where 'gnu' ended up
    count($animals);    // returns 6 
    
    // assign ''
    $animals[2] = '';   // zero out value
    print $animals[2];  // prints ''
    count($animals);    // returns 6, count does not decrease
    

    要将数组压缩为密集填充的数字数组,请使用array_values( )

    $animals = array_values($animals);
    

    或者,array_splice( )自动重新索引数组以避免留下漏洞:

    // create a "numeric" array
        $animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
        array_splice($animals, 2, 2);
        print_r($animals);
        Array
        (
            [0] => ant
            [1] => bee
            [2] => elk
            [3] => fox
        )
    

    如果您将阵列用作队列并希望从队列中删除项目,同时仍允许随机访问,则此选项非常有用 . 要从数组中安全地删除第一个或最后一个元素,请分别使用array_shift( )array_pop( ) .

  • 62

    遵循默认功能

    i)
    
    $Array = array("test1","test2","test3","test3");
    
    unset($Array[2]);
    
    ii)
    
    $Array = array("test1","test2","test3","test3");
    
    array_pop($Array);
    
    iii)
    
    $Array = array("test1","test2","test3","test3");
    
    array_splice($Array,1,2);
    
    iv)
    
    $Array = array("test1","test2","test3","test3");
    
    array_shift($Array);
    
  • 57
    <?php
        $stack = array("fruit1", "fruit2", "fruit3", "fruit4");
        $fruit = array_shift($stack);
        print_r($stack);
    
        echo $fruit;
    ?>
    

    输出:

    Array
    (
        [0] => fruit2
        [1] => fruit3
        [2] => fruit4
    )
    
    fruit1
    
  • 178

    此外,对于命名元素:

    unset($array["elementName"]);
    
  • 13

    您只需使用 unset() 删除数组即可 .

    请记住,在 foreach 函数之后必须取消设置数组 .

  • 6

    Remove an array element based on key:

    使用 unset 函数如下:

    $a = array(
        'salam',
        '10',
        1
    );
    
    unset( $a[1] );
    
    print_r( $a );
    
    /*
    
    Output:
    
    Array
    (
        [0] => salam
        [2] => 1
    )
    
    */
    

    Remove an array element based on value:

    使用 array_search 函数获取元素键并使用上面的方式删除数组元素,如下所示:

    $a = array(
        'salam',
        '10',
        1
    );
    
    $key = array_search( 10, $a );
    
    if( $key !== false ) {
        unset( $a[ $key ] );
    }
    
    print_r( $a );
    
    /*
    
    Output:
    
    Array
    (
        [0] => salam
        [2] => 1
    )
    
    */
    
  • 1

    应该注意的是unset()将保持索引不变,这是您在使用字符串索引(数组作为哈希表)时所期望的,但在处理整数索引数组时可能会非常令人惊讶:

    $array = array(0, 1, 2, 3);
    unset($array[2]);
    var_dump($array);
    /* array(3) {
      [0]=>
      int(0)
      [1]=>
      int(1)
      [3]=>
      int(3)
    } */
    
    $array = array(0, 1, 2, 3);
    array_splice($array, 2, 1);
    var_dump($array);
    /* array(3) {
      [0]=>
      int(0)
      [1]=>
      int(1)
      [2]=>
      int(3)
    } */
    

    因此,如果您想要对整数键进行标准化,则可以使用array_splice() . 另一种选择是在unset()之后使用array_values()

    $array = array(0, 1, 2, 3);
    
    unset($array[2]);
    $array = array_values($array);
    var_dump($array);
    /* array(3) {
      [0]=>
      int(0)
      [1]=>
      int(1)
      [2]=>
      int(3)
    } */
    
  • 4

    我只想说我有一个特定的Object,它有可变属性(它基本上是映射一个表而我正在更改表中的列,所以反映表的对象中的属性也会有所不同

    class obj {
        protected $fields = array('field1','field2');
        protected $field1 = array();
        protected $field2 = array();
        protected loadfields(){} 
        // This will load the $field1 and $field2 with rows of data for the column they describe
        protected function clearFields($num){
            foreach($fields as $field) {
                unset($this->$field[$num]); 
                // This did not work the line below worked
                unset($this->{$field}[$num]); // You have to resolve $field first using {}
            }
        }
    }
    

    $fields 的整个目的只是因为我没有改变,我只是看一下类的开头并更改属性列表和 $fields 数组内容以反映新属性 .

    我花了一点时间想出这个 . 希望这可以帮助别人 .

  • 14
    // our initial array  
       $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");  
      print_r($arr);
    
      // remove the elements who's values are yellow or red  
       $arr = array_diff($arr, array("yellow", "red"));
      print_r($arr);
    

    这是上面代码的输出:

    Array
    (
        [0] => blue
        [1] => green
        [2] => red
        [3] => yellow
        [4] => green
        [5] => orange
        [6] => yellow
        [7] => indigo
        [8] => red
    )
    
    Array
    (
        [0] => blue
        [1] => green
        [4] => green
        [5] => orange
        [7] => indigo
    )
    

    现在,array_values()将很好地重新索引数值数组,但将从数组中删除所有键字符串并用数字替换它们 . 如果需要保留键名(字符串),或者如果所有键都是数字键,则重新索引数组,使用array_merge():

    $arr = array_merge(array_diff($arr, array("yellow", "red")));
    print_r($arr);
    

    输出

    Array
    (
        [0] => blue
        [1] => green
        [2] => green
        [3] => orange
        [4] => indigo
    )
    
  • 2
    unset($array[$index]);
    
  • 6
    $x = array(1, 2, 3, 4, 5);
    var_dump($x);
    unset($x[3]); // here is key to be delete
    echo '<br>';
    array_values($x);
    var_dump($x);
    
  • 12

    两种方法用于删除索引的第一项数据以及如果你不知道第一项的键名 .

    解决方案#1

    // 1 is the index of the first object to get
    // NULL to get everything until the end
    // true to preserve keys
    $array = array_slice($array, 1, null, true);
    

    解决方案#2

    // rewinds array's internal pointer to the first element
    // and returns the value of the first array element. 
    $value = reset( $array );
    // returns the index element of the current array position
    $key = key( $array );
    unset( $array[ $key ]);
    

    对于此示例数据:

    $array = array(10 => "a", 20 => "b", 30 => "c");
    

    您必须有这样的结果:

    array(2) {
      [20]=>
      string(1) "b"
      [30]=>
      string(1) "c"
    }
    
  • 14

    如果你有一个数字索引数组,其中所有值都是唯一的(或者它们是非唯一的,但你希望删除特定值的所有实例),你可以简单地使用array_diff()删除匹配的元素,如下所示:

    $my_array = array_diff($my_array, array('Value_to_remove'));
    

    例如:

    $my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
    echo sizeof($my_array) . "\n";
    $my_array = array_diff($my_array, array('Charles'));
    echo sizeof($my_array);
    

    这显示以下内容:

    4
    3
    

    在此示例中,删除了值为“Charles”的元素,因为sizeof()调用可以验证初始数组的大小为4,删除后的大小为3 .

  • 0
    <?php
    $array = array("your array");
    $array = array_diff($array, ["element you want to delete"]);
    ?>
    

    在变量$ array中创建数组,然后在我放置'要删除的元素'的位置放置类似于“a”的内容 . 如果你想删除多个,那么:“a”,“b” .

  • 14

    如果需要从关联数组中删除多个元素,可以使用array_diff_key()(此处与array_flip()一起使用):

    $my_array = array(
      "key1" => "value 1",
      "key2" => "value 2",
      "key3" => "value 3",
      "key4" => "value 4",
      "key5" => "value 5",
    );
    
    $to_remove = array("key2", "key4");
    
    $result = array_diff_key($my_array, array_flip($to_remove));
    
    print_r($result);
    

    输出:

    Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )
    
  • 1
    // Remove by value
    function removeFromArr($arr, $val)
    {
        unset($arr[array_search($val, $arr)]);
        return array_values($arr);
    }
    
  • 3

    对于关联数组,使用非整数键:

    简单地说, unset($array[$key]) 会起作用 .

    对于具有整数键的数组,如果要维护键:

    • $array = [ 'mango', 'red', 'orange', 'grapes'];

    unset($array[2]); $array = array_values($array);

    • array_splice($array, 2, 1);
  • 2

    unset() 销毁指定的变量 .

    unset() 函数内部的行为可能会有所不同,具体取决于您尝试销毁的变量类型 .

    如果全局变量在函数内部是 unset() ,则仅销毁本地变量 . 调用环境中的变量将保留与调用 unset() 之前相同的值 .

    <?php
    function destroy_foo() 
    {
        global $foo;
        unset($foo);
    }
    
    $foo = 'bar';
    destroy_foo();
    echo $foo;
    ?>
    

    上述代码的答案将是 bar

    unset() 函数内的全局变量

    <?php
    function foo() 
    {
        unset($GLOBALS['bar']);
    }
    
    $bar = "something";
    foo();
    ?>
    
  • 329
    <?php 
    //If you want to remove a particular array element use this method
    $my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
    
    print_r($my_array);
    if(array_key_exists("key1",$my_array)){  
    unset($my_array['key1']);
    print_r($my_array);
    }else{
    echo "Key does not exist";
    }
    ?>
    
    <?php 
    //To remove first array element
    $my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
    print_r($my_array);
    $new_array=array_slice($my_array,1); 
    print_r($new_array);
    ?>
    
    
    <?php 
    echo "
    "; //To remove first array element to length //starts from first and remove two element $my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3"); print_r($my_array); $new_array=array_slice($my_array,1,2); print_r($new_array); ?>

    Output

    Array ( [key1] => value 1 [key2] => value 2 [key3] => 
     value 3 ) Array (    [key2] => value 2 [key3] => value 3 ) 
     Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 ) 
     Array ( [key2] => value 2 [key3] => value 3 )
     Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 ) 
     Array ( [key2] => value 2 [key3] => value 3 )
    
  • 51

    为避免进行搜索,可以使用 array_diff

    $array = array(3, 9, 11, 20);
    $array = array_diff($array, array(11) ); // removes 11
    

    在这种情况下,不必搜索/使用密钥 .

  • 0

    这可能有帮助......

    <?php
        $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
        $a2=array("a"=>"purple","b"=>"orange");
        array_splice($a1,0,2,$a2);
        print_r($a1);
        ?>
    

    结果将是:

    Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
    
  • 27
    $arr = array('orange', 'banana', 'apple', 'raspberry');
    $result= array_pop($arr);
    print_r($result);
    
  • 24

    删除数组元素有不同的方法,其中一些对某些特定任务比其他任务更有用 .

    删除一个数组元素

    如果只想删除一个数组元素,可以使用unset()或替代array_splice() .

    此外,如果您有值并且不知道删除元素的键,则可以使用array_search()来获取密钥 .

    unset()方法

    请注意,当您使用 unset() 时,数组键不会更改/重新索引 . 如果要重新索引键,可以在 unset() 之后使用array_values(),它将所有键转换为从0开始的数字枚举键 .

    <?php
    
        $array = array(0 => "a", 1 => "b", 2 => "c");
        unset($array[1]);
                   //↑ Key which you want to delete
    
    ?>
    

    产量

    Array (
        [0] => a
        [2] => c
    )
    

    array_splice()方法

    如果使用 array_splice() ,键将自动重新索引,但关联键不会改变,而 array_values() 将把所有键转换为数字键 .

    另外 array_splice() 需要偏移量,而不是键!作为第二个参数 .

    <?php
    
        $array = array(0 => "a", 1 => "b", 2 => "c");
        array_splice($array, 1, 1);
                           //↑ Offset which you want to delete
    
    ?>
    

    产量

    Array (
        [0] => a
        [1] => c
    )
    

    array_splice()unset() 相同,通过引用获取数组,这意味着您不希望将这些函数的返回值分配回数组 .

    删除多个数组元素

    如果要删除多个数组元素并且不想多次调用 unset()array_splice() ,则可以使用函数 array_diff()array_diff_key() ,具体取决于您是否知道要删除的元素的值或键 .

    array_diff()方法

    如果您知道要删除的数组元素的值,则可以使用 array_diff() . 和 unset() 一样,它不会改变/重新索引数组的键 .

    <?php
    
        $array = array(0 => "a", 1 => "b", 2 => "c");
        $array = array_diff($array, ["a", "c"]);
                                  //└────────┘→ Array values which you want to delete
    
    ?>
    

    产量

    Array (
        [1] => b
    )
    

    array_diff_key()方法

    如果您知道要删除的元素的键,则需要使用 array_diff_key() . 在这里,您必须确保将键作为键传递给第二个参数而不是值 . 否则,您必须使用array_flip()翻转数组 . 而且这里的密钥不会改变/重新索引 .

    <?php
    
        $array = array(0 => "a", 1 => "b", 2 => "c");
        $array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                                       //↑           ↑ Array keys which you want to delete
    ?>
    

    产量

    Array (
        [1] => b
    )
    

    此外,如果要使用 unset()array_splice() 删除具有相同值的多个元素,可以使用array_keys()获取特定值的所有键,然后删除所有元素 .

  • 6

    unset不会更改索引但array_splice会更改

    $arrayName = array( '1' => 'somevalue',
                            '2' => 'somevalue1',
                            '3' => 'somevalue3',
                            500 => 'somevalue500',
                                 );
    
    
        echo $arrayName['500']; 
        //somevalue500
        array_splice($arrayName, 1,2);
    
        print_r( $arrayName );
        //Array ( [0] => somevalue [1] => somevalue500 )
    
    
    
        $arrayName = array( '1' => 'somevalue',
                            '2' => 'somevalue1',
                            '3' => 'somevalue3',
                            500 => 'somevalue500',
                                 );
    
    
        echo $arrayName['500']; 
        //somevalue500
        unset($arrayName[1]);
    
        print_r( $arrayName );
        //Array ( [0] => somevalue [1] => somevalue500 )
    
  • 1311
    $key = array_search($needle,$array);
    if($key!==false){
        unset($array[$key]);
    }
    
  • 0

    如果您必须删除数组中的多个值,并且该数组中的条目是对象或结构化数据,那么 [array_filter][1] 是您最好的选择 . 将保留那些从回调函数返回true的条目 .

    $array = [
        ['x'=>1,'y'=>2,'z'=>3], 
        ['x'=>2,'y'=>4,'z'=>6], 
        ['x'=>3,'y'=>6,'z'=>9]
    ];
    
    $results = array_filter($array, function($value) {
        return $value['x'] > 2; 
    }); //=> [['x'=>3,'y'=>6,z=>'9']]
    
  • 4

    假设你有这样一个数组:

    Array
    (
        [user_id] => 193
        [storage] => 5
    )
    

    要删除 storage ,请执行以下操作:

    unset($attributes['storage']);
    $attributes = array_filter($attributes);
    

    你得到:

    Array
    (
        [user_id] => 193
    )
    
  • 0

    关联数组

    对于关联数组,请使用unset

    $arr = array('a' => 1, 'b' => 2, 'c' => 3);
    unset($arr['b']);
    
    // RESULT : array('a' => 1, 'c' => 3)
    

    数字数组

    对于数字数组,请使用array_splice

    $arr = array(1, 2, 3);
    array_splice($arr, 1, 1);
    
    // RESULT : array(0 => 1, 1 => 3)
    

    注意

    使用unset进行数值数组不会产生错误,但会使索引陷入困境:

    $arr = array(1, 2, 3);
    unset($arr[1]);
    
    // RESULT : array(0 => 1, 2 => 3)
    

相关问题