How to Delete an Element from an Array in PHP

  1. Using the unset() Method
  2. Using the array_splice() Method

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.

A. Using the unset() Function

Normally, the unset() function is used for that aim.

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

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

B. 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:

. <?php
. $arr = array(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.


Do you find this helpful?

Related articles