Easy Ways to Delete an Item from an Array in PHP

In PHP, there are several methods to remove elements from an array. Here are some easy approaches to delete items from an array:

  1. Using unset() Function:
    The unset() function is the simplest way to remove an element by its index. However, it doesn’t reindex the array.

Example:

<?php
$arr = array(1, 2, 3, 4, 5);
// Removes the element at index 2
unset($arr[2]);
print_r($arr);
?>

//Output

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)
  1. Using array_splice() Function:
    The array_splice() function removes a portion of the array and reindexes the remaining elements.

Example:

<?php
$arr = array(1, 2, 3, 4, 5);
// Removes 1 element starting at index 2
array_splice($arr, 2, 1);
print_r($arr);
?>

//Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
)
  1. Using array_diff() Function:
    array_diff() compares arrays and returns the values that are not present in the comparison array, effectively removing the specified values.

Example:

<?php
$arr = array(1, 2, 3, 4, 5);
// Removes the value 3
$arr = array_diff($arr, array(3));
print_r($arr);
?>

//Output

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)
  1. Using array_filter() Function:
    array_filter() applies a callback function to filter out elements that match a specific condition.

Example:

<?php
$arr = array(1, 2, 3, 4, 5);
// Remove the element with value 3
$arr = array_filter($arr, function($value) {
    return $value != 3;
});
print_r($arr);
?>

//Output

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)
  1. Using array_search() and unset() Functions:
    Combine array_search() to find the index of a value and unset() to remove the element.

Example:

<?php
$arr = array(1, 2, 3, 4, 5);
// Find the index of the value 3
$key = array_search(3, $arr);
if ($key !== false) {
    unset($arr[$key]);
}
print_r($arr);
?>

//Output

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)
  1. Using a Loop to Remove Multiple Occurrences:
    If you need to remove all occurrences of a value from an array, use a loop and unset().

Example:

<?php
$arr = array(1, 2, 3, 4, 3, 5);
$remVal = 3;
foreach ($arr as $key => $value) {
    if ($value == $remVal) {
        unset($arr[$key]);
    }
}
print_r($arr);
?>

//Output

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [5] => 5
)

Keep Learning 🙂

Leave a Reply

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