How To Remove Key From Array In Php

When working with arrays in PHP, you might sometimes need to remove certain elements by their keys. This can be achieved using the unset() function, which allows you to remove an array element by specifying its key.

Using the unset() Function

The unset() function is used to remove a variable or an array element, and its use is quite simple. The syntax for the function is as follows:

unset($array[$key]);

Here, $array is the array you want to remove an element from, and $key is the index or key of the element you want to remove. Let’s look at an example:

Example 1

Suppose you have the following array:

$animals = array("Dog", "Cat", "Elephant", "Tiger", "Lion");

Let’s say you want to remove the element “Elephant” from the array. You can use the unset() function as shown below:

After executing this code, you’ll get the following output:

Array ( [0] => Dog [1] => Cat [3] => Tiger [4] => Lion )

As you can see, the “Elephant” element has been removed from the array. Note that the keys are preserved, so the key “2” is missing from the output.

Reindexing the Array

If you want to reindex the array after removing the element, you can use the array_values() function. This function returns all the values of an array and reindexes the keys. Here’s an example:

Example 2

After executing this code, you’ll get the following output:

Array ( [0] => Dog [1] => Cat [2] => Tiger [3] => Lion )

Now the keys are reindexed, and the array is in a continuous sequence.

Conclusion

In this blog post, we’ve covered how to remove an element from an array in PHP using the unset() function. We’ve also demonstrated how to reindex the array keys after removing an element using the array_values() function. With these tools in hand, you can easily manipulate arrays in PHP to fit your needs.