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.
This may help...
result will be:
Also, for a named element:
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Delete one array element
If you want to delete just one array element you can use
unset()
or alternativearray_splice()
.Also if you have the value and don't know the key to delete the element you can use
array_search()
to get the key.unset()
methodNote that when you use
unset()
the array keys won't change/reindex. If you want to reindex the keys you can usearray_values()
afterunset()
which will convert all keys to numerical enumerated keys starting from 0.Code
Output
array_splice()
methodIf you use
array_splice()
the keys will be automatically reindexed, but the associative keys won't change as opposed toarray_values()
which will convert all keys to numerical keys.Also
array_splice()
needs the offset, not the key! as the second parameter.Code
Output
array_splice()
same asunset()
take the array by reference, this means you don't want to assign the return values of those functions back to the array.Delete multiple array elements
If you want to delete multiple array elements and don't want to call
unset()
orarray_splice()
multiple times you can use the functionsarray_diff()
orarray_diff_key()
depending on if you know the values or the keys of the elements which you want to delete.array_diff()
methodIf you know the values of the array elements which you want to delete, then you can use
array_diff()
. As before withunset()
it won't change/reindex the keys of the array.Code
Output
array_diff_key()
methodIf you know the keys of the elements which you want to delete, then you want to use
array_diff_key()
. Here you have to make sure you pass the keys as keys in the second parameter and not as values. Otherwise, you have to flip the array witharray_flip()
. And also here the keys won't change/reindex.Code
Output
Also if you want to use
unset()
orarray_splice()
to delete multiple elements with the same value you can usearray_keys()
to get all the keys for a specific value and then delete all elements.