How to Delete an Element from an Array in PHP

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 unset() function is used for that aim. It removes an element from an array using it's 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:


  $arr1 = ["a" => "Apple", "b" => "Ball", "c" => "Cat"];
  // RESULT: array("a" => "Apple", "c" => "Cat")
  $arr2 = [1, 2, 3];
  // 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 array_splice() function. It includes the following three parameters: an array, offset, and the length. It works like this:


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


Definition of the PHP Unset() Function

Unset() is considered a PHP predefined variable function for unsetting a certain variable. In other words, this function is used for destroying the variables. Its behavior varies within the user-defined function. In case a global variable is unset within a function, the unset will destroy it locally, leaving the same value provided for outside, initially.