1. unset() – Remove by Key/Index
The unset() function is perfect when you need to remove specific elements by their keys or indexes. It’s important to note that this method doesn’t reindex the array, so you’ll need to handle that separately if needed.
1 2 3 |
$array = ['a', 'b', 'c', 'd']; unset($array[1]); // Removes 'b' // Result: [0 => 'a', 2 => 'c', 3 => 'd'] |
2. array_splice() – Remove and Reindex
When you need to remove elements and automatically reindex the array, array_splice() is your best choice. This function is particularly useful when working with numerically indexed arrays where maintaining sequence is important.
1 2 3 |
$array = ['a', 'b', 'c', 'd']; array_splice($array, 1, 1); // Removes 1 element at index 1 ('b') // Result: [0 => 'a', 1 => 'c', 2 => 'd'] |
3. array_diff() – Remove by Value
If you need to remove elements based on their values rather than keys, array_diff() provides an elegant solution. This method compares your array against another array of values to remove, preserving the original keys.
1 2 3 |
$array = ['a', 'b', 'c', 'd']; $array = array_diff($array, ['b']); // Removes 'b' // Result: [0 => 'a', 2 => 'c', 3 => 'd'] |
4. array_filter() – Conditional Removal
For more complex removal scenarios where you need to evaluate each element, array_filter() is incredibly powerful. You can define custom logic to determine which elements to keep or remove from your array.
1 2 3 4 5 |
$array = [1, 2, 3, 4, 5]; $array = array_filter($array, function($value) { return $value % 2 == 0; // Keep even numbers }); // Result: [1 => 2, 3 => 4] |
5. Remove First/Last Elements
PHP provides dedicated functions for working with the beginning and end of arrays. These are particularly useful when implementing queue or stack-like behavior in your applications.
1 2 3 4 5 |
// Remove first element array_shift($array); // Remove last element array_pop($array); |
6. Remove and Get Element
Sometimes you need both to remove an element and use its value. These functions not only remove elements from the array but also return the removed value, which can be stored in a variable.
1 2 3 4 5 |
// Remove and return first element $first = array_shift($array); // Remove and return last element $last = array_pop($array); |
7. Reindexing After Removal
After using unset() or array_diff(), you might need to reset your array keys to a continuous numerical sequence. The array_values() function creates a new array with sequential numerical indexes starting from zero.
1 2 3 4 |
$array = ['a', 'b', 'c', 'd']; unset($array[1]); $array = array_values($array); // Reindex // Result: [0 => 'a', 1 => 'c', 2 => 'd'] |