4.5. Deleting Elements from an Array
Problem
You want to remove one or more elements from an array.
Solution
To delete one element, use unset( ):
unset($array[3]); unset($array['foo']);
To delete multiple noncontiguous elements, also use unset( ):
unset($array[3], $array[5]); unset($array['foo'], $array['bar']);
To delete multiple contiguous elements, use array_splice( ):
array_splice($array, $offset, $length);
Discussion
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access