How to delete an element from an array in PHP?

To delete an element from an array in PHP, use one of the following methods based on your specific needs:

1. Remove by Key (Index)

Using unset()

Removes an element by its key. Does not reindex the array (leaves a gap in numeric keys).

$array = ['a', 'b', 'c'];
unset($array[1]); // Removes element at index 1
// Result: [0 => 'a', 2 => 'c']

Reindex Numeric Arrays

If you need sequential numeric keys after deletion:

$array = ['a', 'b', 'c'];
unset($array[1]);
$array = array_values($array); // Reindexes keys to [0, 1]
// Result: [0 => 'a', 1 => 'c']

2. Remove by Value

Using array_search() + unset()

Finds the key of the first matching value and removes it.

$array = ['a', 'b', 'c'];
$key = array_search('b', $array); // Returns index 1
if ($key !== false) {
    unset($array[$key]);
}
// Result: [0 => 'a', 2 => 'c']

Using array_diff()

Removes all occurrences of a value (returns a new array).

$array = ['a', 'b', 'c'];
$array = array_diff($array, ['b']);
// Result: [0 => 'a', 2 => 'c']

3. Remove by Position (Numeric Arrays)

Using array_splice()

Removes elements by offset and reindexes the array.

$array = ['a', 'b', 'c'];
array_splice($array, 1, 1); // Removes 1 element starting at index 1
// Result: [0 => 'a', 1 => 'c']

4. Remove via Conditional Logic

Using array_filter()

Creates a new array by filtering out unwanted values (preserves keys).

$array = ['a', 'b', 'c'];
$array = array_filter($array, function($value) {
    return $value !== 'b';
});
// Result: [0 => 'a', 2 => 'c']

Key Differences

MethodUse CaseReindexes?Key Handling
unset()Remove by key (numeric/associative).❌ NoLeaves gaps in numeric keys.
array_values()Reset numeric keys after unset().✅ YesConverts to sequential numeric keys.
array_search()Remove by value (first occurrence).❌ NoRequires unset() afterward.
array_diff()Remove all instances of a value.❌ NoReturns a new array.
array_splice()Remove by position (numeric arrays).✅ YesReindexes automatically.
array_filter()Remove elements via a callback.❌ NoPreserves original keys.

Example Workflow

// Original array
$fruits = ['apple', 'banana', 'cherry'];

// Remove 'banana' by value and reindex
$key = array_search('banana', $fruits);
if ($key !== false) {
    unset($fruits[$key]);
    $fruits = array_values($fruits); // Reindex
}

// Output: ['apple', 'cherry']
print_r($fruits);

When to Use Which

  • Associative Arrays: Use unset($array['key']) to remove elements by key.
  • Numeric Arrays: Use array_splice() to remove elements by position and reindex.
  • Remove by Value: Use array_search() + unset() for single values or array_diff() for multiple values.
  • Conditional Removal: Use array_filter() for complex criteria.

Choose the method that best fits your use case!

Leave a Reply

Your email address will not be published. Required fields are marked *