How to Delete an Element From an Array In PHP?

Problem:

You want to delete an element from an array. You’re looking for an easy solution for it.

Solution:

Use unset() function.

Example:

The following example shows how to remove Wednesday from the array $week.

<pre>
<?php
$week = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
unset($week[2]);
print_r($week);
?>
</pre>

Output:
Array
(
[0] => Monday
[1] => Tuesday
[3] => Thursday
[4] => Friday
[5] => Saturday
[6] => Sunday
)

How it works

Line 3 Array $week contains seven days
Line 4 Wednesday is in the index no 2(php array starts from index 0) in the array $week. So, to delete Wednesday, we use $week[2].
Line 5 print_r() prints the array in readable format that you see in the output.

In the output of the above example, after using unset() in the new array the index or key of the removed element (which is 2) is also removed. So, we don’t see index [2].
To sort the index serially in the output array, we can use one of the following two ways-

  • Use array_values() function after using unset() (See the first example below) or
  • Use array_splice() function only(See the second example below).

Method 1: Using array_values() function after applying unset() to serialize the indexes.

<pre>
<?php
$week = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
unset($week[2]);
$week = array_values($week);
print_r($week);
?>
</pre>

Output:
Array
(
[0] => Monday
[1] => Tuesday
[2] => Thursday
[3] => Friday
[4] => Saturday
[5] => Sunday
)
How it works:

Line 5 Function array_values() returns an array where index starts at 0 and increases by 1. That’s why we see in the above out that the indexes are serially from 0 to 5
Line 6 print_r() prints the array in readable format that you see in the output.

 

Method 2: Using array_splice() function to serialize the indexes

<pre>
<?php
$week = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
array_splice($week, 2, 1);
print_r($week);
?>
</pre>

Output:
Array
(
[0] => Monday
[1] => Wednesday
[2] => Thursday
[3] => Friday
[4] => Saturday
[5] => Sunday
)

How it works:

Line 4 Function array_splice() starts removing one element(which is referred  in the third parameter by 1) from the array $week (which is the first parameter) starts at index 2 (which is referred in the second parameter). So, it removes Wednesday.
Line 5 print_r() prints the array in readable format that you see in the output.