PHP Delete Array Items

To delete items from an array in PHP, you can use several methods depending on how you want to remove the items. Here are common examples:


1. Using unset() – Remove by key or index:

$array = ['a', 'b', 'c', 'd']; unset($array[1]); // Removes 'b' print_r($array);

 Note: unset() does not reindex the array. If you need reindexing, use array_values().

$array = array_values($array); // Optional reindexing

2. Using array_splice() – Remove by index and reindex:

$array = ['a', 'b', 'c', 'd']; array_splice($array, 1, 1); // Removes 'b' print_r($array);

3. Using array_diff() – Remove by value:

$array = ['a', 'b', 'c', 'd']; $array = array_diff($array, ['b']); // Removes all 'b' print_r($array);

4. Using a foreach loop – Conditional deletion:

$array = [1, 2, 3, 4, 5]; foreach ($array as $key => $value) { if ($value % 2 == 0) { unset($array[$key]); // Remove even numbers } } print_r($array);