There are several ways to work with arrays in PHP. We may try to remove an entry from an array based on its key as one form of array manipulation.
In PHP, our array may be a collection of key-value pairs or a list of items that are sequentially ordered. Let’s look at how to remove an element from an array in PHP using its key.
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 illustration, the array contains a number of key-value pairs. The key-value pair with the key “example” has to be deleted. The unset PHP method will be used to do this.
unset($array['example']);
This straightforward technique removes a value by its key as well as a component from a sequential array.
$array = array('A','B','C');
The sequential array is used in this case. Any piece may also be removed based on its placement. The following code would be used to eliminate the second member “B” from the list.
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.