Deleting an element from an array in PHP

后端 未结 30 3357
时光说笑
时光说笑 2020-11-21 05:55

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it

相关标签:
30条回答
  • 2020-11-21 06:48
    // Remove by value
    function removeFromArr($arr, $val)
    {
        unset($arr[array_search($val, $arr)]);
        return array_values($arr);
    }
    
    0 讨论(0)
  • 2020-11-21 06:48

    I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):

    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 {}
            }
        }
    }
    

    The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.

    0 讨论(0)
  • 2020-11-21 06:50

    Suppose you have the following array:

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

    To delete storage, do:

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

    And you get:

    Array
    (
        [user_id] => 193
    )
    
    0 讨论(0)
  • 2020-11-21 06:50

    Use the following code:

    $arr = array('orange', 'banana', 'apple', 'raspberry');
    $result = array_pop($arr);
    print_r($result);
    
    0 讨论(0)
  • 2020-11-21 06:51

    unset() multiple, fragmented elements from an array

    While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:

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

    unset() dynamically

    unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).

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

    Instead, unset() can be used dynamically in a foreach loop:

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

    Remove array keys by copying the array

    There is also another practice that has yet to be mentioned. Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $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 ];
    

    Obviously, the same practice applies to text strings:

    $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' ]
    
    0 讨论(0)
  • 2020-11-21 06:51

    For associative arrays, with non-integer keys:

    Simply, unset($array[$key]) would work.

    For arrays having integer keys and if you want to maintain your keys:

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

      unset($array[2]);
      $array = array_values($array);
      
    2. array_splice($array, 2, 1);

    0 讨论(0)
提交回复
热议问题