W3docs

How to Delete an Element from an Array in PHP

In this short tutorial, you will find the most proper solution to the commonly asked question by programmers: how to delete an element from an array.

One of the most common tasks in PHP is deleting an element from an array. This short tutorial will explain to you in detail how to do it.

Using the unset() Function

Normally, the <kbd class="highlighted">unset()</kbd> language construct is used for that purpose. It removes an element from an array using its index. If the provided index does not exist, it skips the procedure and does nothing.

Here is a clear example, showing how to delete an element from an array:

php delete an element from array

<?php

  $arr1 = ["a" => "Apple", "b" => "Ball", "c" => "Cat"];
  unset($arr1["b"]);
  var_dump($arr1);
  // RESULT: array("a" => "Apple", "c" => "Cat")
  $arr2 = [1, 2, 3];
  unset($arr2[1]);
  var_dump($arr2);
  // RESULT: array(0 => 1, 2 => 3)

?>

Using the array_splice() Method

But, after observing this example carefully, you can notice that the array isn’t reindexed by the function after removing the value from the numeric array. To settle that, you can apply the <kbd class="highlighted">array_splice()</kbd> function. It includes the following three parameters: an array, offset, and the length. It works like this:

php array_splice function

<?php

  $arr = [1, 2, 3];
  array_splice($arr, 1, 1);
  var_dump($arr);
  // RESULT: array(0 => 1, 1 => 3)

?>