Removing Array Element and Re-Indexing in PHP
In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically.
Function Used:
- unset(): This function unsets a given variable.
Syntax:void unset ( mixed $var [, mixed $... ] )
- array_values(): This function returns all the values from the array and indexes the array numerically.
Syntax:
array array_values ( array $array )
Example 1:
<?php $arr1 = array( 'geeks', // [0] 'for', // [1] 'geeks' // [2] ); // remove item at index 1 which is 'for' unset($arr1[1]); // Print modified array var_dump($arr1); // Re-index the array elements $arr2 = array_values($arr1); // Print re-indexed array var_dump($arr1); ?> |
chevron_right
filter_none
Output:
array(2) {
[0]=>
string(5) "geeks"
[2]=>
string(5) "geeks"
}
array(2) {
[0]=>
string(5) "geeks"
[2]=>
string(5) "geeks"
}
We can also use array_splice() function which removes a portion of the array and replaces it with something else.
Example 2:
<?php $arr1 = array( 'geeks', // [0] 'for', // [1] 'geeks' // [2] ); // remove item at index 1 which is 'for' array_splice($arr1, 1, 1); // Print modified array var_dump($arr1); ?> |
chevron_right
filter_none
Output:
array(2) {
[0]=>
string(5) "geeks"
[1]=>
string(5) "geeks"
}
Recommended Posts:
- Reindexing in Pandas DataFrame
- Array formed from difference of each element from the largest element in the given array
- Replace each element by the difference of the total size of the array and frequency of that element
- Replace every array element by Bitwise Xor of previous and next element
- Replace every element of the array by its previous element
- Average of remaining elements after removing K largest and K smallest elements from array
- Replace every element of the array by its next element
- How to move an array element from one array position to another in JavaScript?
- How to get the first element of an array in PHP?
- PHP | Second most frequent element in an array
- Count of even and odd set bit with array element after XOR with K
- Find the min/max element of an Array using JavaScript
- Searching in Array for a given element in Julia
- PHP | Deleting an element from array using array_diff()
- How to remove an element from an array in JavaScript?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

