Skip to main content Skip to course navigation

Removing Array Items

PHP gives you several ways to remove items from arrays, and each method behaves differently. Understanding when to use each one is important.

array_splice() removes and reindexes:

This function removes items starting at a specific position and automatically reindexes the array so there are no gaps. You specify where to start and how many items to remove. Use this when you want a clean, sequential array after deletion.

unset() removes but leaves gaps:

This deletes an item at a specific index or key but doesn’t reindex the array. You can end up with arrays like [0 => "first", 2 => "third", 3 => "fourth"] where index 1 is missing. For associative arrays, this is fine since keys are names anyway. For indexed arrays, only use this if you don’t care about gaps.

You can delete multiple items at once: unset($cars[0], $cars[1], $cars[5]).

array_diff() filters by value:

Give it a list of values to remove, and it returns a new array without those values. It compares the actual values, not their positions or keys. Useful when you know what to remove but not where it is.

array_pop() and array_shift() remove ends:

array_pop() removes and returns the last item. array_shift() removes and returns the first item. Both are simple, single-purpose functions for common operations.