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
// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
This is the output from the code above:
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
Outputs
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)