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 to null
would do it, but apparently it does not work.
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 to null
would do it, but apparently it does not work.
If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:
For example:
This displays the following:
In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.
Solutions:
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:
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 saysThis 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:
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:
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:
To compact the array into a densely filled numeric array, use array_values( ):
Alternatively, array_splice( ) automatically reindexes arrays to avoid leaving holes:
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.
If you have to delete multiple values in an array and the entries in that array are objects or structured data,
[array_filter][1]
is your best bet. Those entries that return a true from the callback function will be retained.Follow default functions