How to Delete or Remove Array Element By Value in PHP

Last Updated on June 19, 2021 by Roshan Parihar

In this tutorial, learn how to delete or remove array element by value using PHP. The short answer is to use the unset() function of PHP that takes array variable with key as an argument.

You can also use the array_splice() method to remove the specified element from an array in PHP. Let’s find out different methods with examples given below here.

Method 1: Using unset() to Remove Array Element By Value in PHP

To remove the given element from an array by value, you have to first find the index of the element or the key. You can identify the index or key of the element using the array_search() as given below. After that, you have to use the unset() function to remove the specified element from an array.

Output

Array ( [0] => Cycle [2] => Car [3] => Bolero )

The above example shows the output that is an array with the element “Bike” remove from it. The resulted array is not in the proper sequence of indexing. You can use the next method to make the array in proper sequence.

Method 2: Using array_splice() to Delete an Element From an Array in PHP

When you want to delete an element from an array, you can use the array_splice() that also gives a proper sequence of indexing in the output. Firstly, you have to find the index or key of the given element using the array_search(). After that, you can use the array_splice() function given below to delete an element from an array.

The array_splice() function takes three arguments to pass. The first argument is the array variable. The second argument is the key that is the result of array_search() function. The third argument of the function specifies the number of elements you want to delete from an array. As you have to delete only a single given element from an array. That’s why the third argument is 1.

Output

Array ( [0] => Cycle [1] => Car [2] => Bolero )

The above example resulted in the array that is in the proper sequence of indexing after the element gets deleted.

Method 3: Using For Loop with unset()

In addition to the above methods, you can also use the for loop of PHP with the unset() function to eliminate the element from an array. You have to match the value of each array element with the given value on each iteration of the loop using the if condition. See the example given below to learn the method.

Output

Array ( [0] => Cycle [2] => Car [3] => Bolero )

The above example shows the output that contains the array after eliminating the given element from it.

You can use any of the methods given above. However, if you want the array in the output should be a proper sequence of indexing, you can use the second example using array_splice() function.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.