How to Delete an element from an Array in PHP

Indeed, You (developers) may be frequently encountered to delete an element from an array in PHP. Of course, There are several ways to delete an element from an array in PHP. In this guide, we will explore some of the most common methods.

1. Delete an element from an Array

Firstly, You can use the unset() function. Above all, the unset() is a built-in function in PHP that is used to remove an element from an array. Therefore, you need to specify the index of the element that you want to remove. For example, suppose we have an array called $myArray with the following elements:

$myArray = array('apple', 'banana', 'orange', 'grape');

To delete the ‘banana’ element from the array, you can use the following code:

unset($myArray[1]);

In this code, we are using the unset() function to remove the element with index 1, which is ‘banana’. After executing this code, the $myArray will have the following elements:

array('apple', 'orange', 'grape');

PHP Array_Splice() Function

The array_splice() function is another built-in function in PHP that can be used to remove an element from an array. Unlike the unset() function, the array_splice() function can remove an element and re-index the remaining elements in the array. To delete an element from an array using the array_splice() function, you need to specify the index of the element that you want to remove and the number of elements you want to remove. For example, suppose we have the same $myArray as before, and we want to remove the ‘banana’ element using the array_splice() function. The code would look like this:

array_splice($myArray, 1, 1);

In this code, we are using the array_splice() function to remove one element starting from index 1, which is ‘banana’. After executing this code, the $myArray will have the following elements:

array('apple', 'orange', 'grape');

In conclusion, deleting an element from an array in PHP can be achieved using either the unset() function or the array_splice() function. Both methods are easy to use and can be applied in various situations depending on your requirements.

Share

You may also like...