This question has several answers but I want to add something more because when I used unset
or array_diff
I had several problems to play with the indexes of the new array when the specific element was removed (because the initial index are saved)
I get back to the example :
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));
or
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);
If you print the result you will obtain :
foreach ($array_without_strawberries as $data) {
print_r($data);
}
Result :
> apple
> orange
> blueberry
> kiwi
But the indexes will be saved and so you will access to your element like :
$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi
And so the final array are not re-indexed. So you need to add after the unset
or array_diff
:
$array_without_strawberries = array_values($array);
After that your array will have a normal index :
$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi
Related to this post : Re-Index Array
Hope it will help