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.
It should be noted that
unset()
will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:So
array_splice()
can be used if you'd like to normalize your integer keys. Another option is usingarray_values()
afterunset()
:Suppose you have such an array:
To delete
storage
, do:And you get:
Output:
unset()
destroys the specified variables.The behavior of
unset()
inside of a function can vary depending on what type of variable you are attempting to destroy.If a globalized variable is
unset()
inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as beforeunset()
was called.The Answer of the above code will be bar
To
unset()
a global variable inside of a functionAssociative arrays
For associative arrays, use
unset
:Numeric arrays
For numeric arrays, use
array_splice
:Note
Using
unset
for numeric arrays will not produce an error, but it will mess up your indexes :If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):
Output: