0
0
PhpHow-ToBeginner · 3 min read

How to Remove Element from Array in PHP: Simple Methods

To remove an element from an array in PHP, use unset() with the element's key to delete it directly. Alternatively, use array_splice() to remove elements by position or array_filter() to remove elements by condition.
📐

Syntax

Here are common ways to remove elements from arrays in PHP:

  • unset($array[key]); - Removes element by key.
  • array_splice($array, offset, length); - Removes elements by position.
  • array_filter($array, callback); - Removes elements based on a condition.
php
<?php
// Remove element by key
unset($array['key']);

// Remove elements by position
array_splice($array, 2, 1); // removes 1 element at index 2

// Remove elements by condition
$array = array_filter($array, fn($value) => $value !== 'remove');
?>
💻

Example

This example shows how to remove an element by key, by position, and by condition from an array.

php
<?php
// Original array
$fruits = ['apple', 'banana', 'cherry', 'date', 'banana'];

// Remove element by key (remove 'cherry')
unset($fruits[2]);

// Remove element by position (remove element at index 1, 'banana')
array_splice($fruits, 1, 1);

// Remove elements by condition (remove all 'banana')
$fruits = array_filter($fruits, fn($fruit) => $fruit !== 'banana');

// Reindex array to have consecutive keys
$fruits = array_values($fruits);

// Print result
print_r($fruits);
?>
Output
Array ( [0] => apple [1] => date )
⚠️

Common Pitfalls

Common mistakes when removing elements from arrays in PHP include:

  • Using unset() but forgetting it does not reindex numeric keys, which can cause gaps.
  • Trying to remove elements by value without a condition or loop.
  • Not reindexing arrays after removal when numeric keys are important.

Always use array_values() to reindex if needed.

php
<?php
// Wrong: unset does not reindex keys
$array = ['a', 'b', 'c'];
unset($array[1]);
print_r($array); // keys: 0, 2

// Right: reindex after unset
$array = array_values($array);
print_r($array); // keys: 0, 1
?>
Output
Array ( [0] => a [2] => c ) Array ( [0] => a [1] => c )
📊

Quick Reference

MethodDescriptionExample
unset()Removes element by keyunset($array[2]);
array_splice()Removes elements by positionarray_splice($array, 1, 2);
array_filter()Removes elements by conditionarray_filter($array, fn($v) => $v !== 'x');
array_values()Reindexes numeric keys$array = array_values($array);

Key Takeaways

Use unset() to remove an element by its key but remember it does not reindex numeric keys.
Use array_splice() to remove elements by their position in the array.
Use array_filter() with a callback to remove elements based on a condition.
Call array_values() to reindex arrays after removals if numeric keys matter.
Always check your array keys after removal to avoid unexpected gaps.