Deleting an element from an array in PHP

后端 未结 30 3282
时光说笑
时光说笑 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:34

    Solutions:

    1. To delete one element, use unset():
    unset($array[3]);
    unset($array['foo']);
    
    1. To delete multiple noncontiguous elements, also use unset():
    unset($array[3], $array[5]);
    unset($array['foo'], $array['bar']);
    
    1. To delete multiple contiguous elements, use array_splice():
    array_splice($array, $offset, $length);
    

    Further explanation:

    Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:

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

    Besides syntax, there's a logical difference between using unset() and assigning '' to the element. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.

    If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:

    unset($products['XL1000']);
    

    However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:

    $products['XL1000'] = 0;
    

    If you unset() an element, PHP adjusts the array so that looping still works correctly. It doesn'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's an example:

    // 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 a new element
    $animals[ ] = 'gnu'; // Add a 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
    

    To compact the array into a densely filled numeric array, use array_values():

    $animals = array_values($animals);
    

    Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:

    // 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
    )
    

    This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift() and array_pop(), respectively.

提交回复
热议问题