How to Delete an Element by Key from an Array in PHP

PHP Delete Key Array Featured

PHP provides you with many methods to manipulate arrays. One type of array manipulation we may look to do is delete an element by its key. Our array could be a sequential list of values in PHP, but it could also be a collection of key-value pairs. Let’s take a look at how to delete an element by key from an array in PHP. 

Solution

First, we can take a look at the key-value example. 

$array = array('hello' => 'world', 'example' => 'value', 'one' => 'more');

In this example, we have a collection of key-value pairs in the array. We want to remove the key-value pair with the key of “example“. In order to do this, we will use the unset PHP method

unset($array['example']);

This simple method will remove the value by its key, but it will also remove an element from a sequential array. 

$array = array('A','B','C');

This example is a sequential array. We can remove any element by its position as well. If we wanted to remove the second element “B” from the list, we would use the following code. 

unset($array[1])

That’s all there is to it. A simple one-liner does the trick to delete an element by key from an array in PHP.

Check out our other PHP how-to’s:

How to check if an array has more than one element in PHP

Disclaimer: Some posts on Techozu may contain affiliate links. Purchasing through these links may earn us an affiliate commission.