Arrays store the element together using an index based system, starting from 0. While we can simply set the value to NULL, but it will still be the part of the array and take up space in memory. But using the advanced PHP built-in methods we can easily delete an element from an array. There are 2 ways of deleting an element from the array in PHP which are discussed below.
1) Using unset()
The unset() method takes the element which needs to be deleted from the array and deletes it. Note that, when you use unset() the array keys won't re-index, which means there will be no particular index present in that array and if accessed will not return a value. Consider this example,
Code
We define an associative array using the key as the index and unset the second element from it. Now we are left with two elements with no second index between them. If we want to remove as well as shift the elements, we need to use the array_splice method discussed below.
2) Using array_splice()
It does the same work as the unset() except that it rearranges and shift the elements to fill the empty space. If you use array_splice() the keys will be automatically reindexed, but the associative keys won't change opposed to array_values() which will convert all keys to numerical keys.
Also, array_splice() needs the offset as second parameter, which means number of elements to be deleted.
Code
As we can see from output, the array deleted the second element but re-indexed the array thereafter.
If you like the article, share your thoughts below.
need an explanation for this answer? contact us directly to get an explanation for this answer