Is there an easy way to remove an element from a PHP array, such that it foreach ($array)
no longer includes that element?
I thought setting it to null would do it, but apparently not.
Is there an easy way to remove an element from a PHP array, such that it foreach ($array)
no longer includes that element?
I thought setting it to null would do it, but apparently not.
If you have a numerically indexed array where all the values are unique (or not unique but you want to remove all instances of a particular value), you can simply use
array_diff()
to remove a matching element, like this:For example:
This shows the following:
In this example, the element with the value 'Charles' is removed as can be verified by the calls
sizeof()
that report a size of 4 for the initial array and 3 after removal.A. If you want to remove all occurrences of the value within the array
You can combine the following PHP functions:
array_keys()
andunset()
In the example I have implemented the function
remover()
:See DEMO of solutions A and B
Result:
B. If you want to remove only one occurrence:
You can combine
unset()
quoted above, witharray_search()
.Example:
Result:
A simple way is using the "unset" function, I suppose you are working with "JSON" format since it is widely used nowadays:
The syntax:
here another solution, it can be useful to another person who is looking for
//delete elements of the first array that are equal to those of the second array
the output of this would be: Array ( [2] => 3 )
It will depend on the situation you are in:
I want to remove an element whose index is known ...
...
What I want is to remove a value from the array. In this case, since there can be several, I can locate them with an option to search for the position of that value, since there can be several, we will have to iterate...
...