How to Remove and Reindex an Array Element in PHP
Sometimes, in the course of working with PHP, it is necessary to remove and reindex an array element. Here, you will find simple and helpful methods to do that.
Sometimes, in the course of working with PHP, it is necessary to remove and reindex an array element. Here, we have gathered helpful approaches that will help to achieve that.
Using unset() and array_values()
In this section, we will proceed with removing an array element with the <kbd class="highlighted">unset()</kbd> function and, then, reindexing it with <kbd class="highlighted">array_values()</kbd>.
The <kbd class="highlighted">unset()</kbd> function is used for unsetting a given variable.
The syntax is the following:
How to Remove and Reindex an Array Element in PHP?
unset(mixed $var, mixed ...$vars): voidThe <kbd class="highlighted">array_values()</kbd> function is aimed at returning all the values from the array and numerically indexing the array.
The syntax is the following:
Example of removing and reindexing an Array element in PHP
array array_values ( array $array )Now, let’s see how these two functions look like in action:
php unset() and array_values()
<?php
$arr1 = [
'w3docs', // [0]
'for', // [1]
'w3docs', // [2]
];
// remove the item at index 1, which is 'for'
unset($arr1[1]);
// Print modified array
var_dump($arr1);
// Reindex the array elements
$arr2 = array_values($arr1);
// Print re-indexed array
var_dump($arr2);php unset() and array_value() usage output
array(2) {
[0]=>
string(6) "w3docs"
[2]=>
string(6) "w3docs"
}
array(2) {
[0]=>
string(6) "w3docs"
[1]=>
string(6) "w3docs"
}Using array_splice()
There is an alternative solution, too. It’s using the <kbd class="highlighted">array_splice()</kbd> function, which is used for removing a part of an array and replacing it with anything else.
The syntax of this function is the following:
php array_splice() function
array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] ) : arrayFor a better perception of how this function works, check out the example below:
php use array_splice() function
<?php
$arr1 = [
'w3docs', // [0]
'for', // [1]
'w3docs', // [2]
];
// remove item at index 1 which is 'for'
array_splice($arr1, 1, 1);
// Print modified array
var_dump($arr1);array(2) {
[0]=>
string(6) "w3docs"
[1]=>
string(6) "w3docs"
}PHP Arrays
An array is a variable that contains a collection of other values, available on specific indices. To access the value of an array, we need to specify the name of the array and the index of the data.
The <kbd class="highlighted">array()</kbd> function or <kbd class="highlighted">[]</kbd> are used for generating an array in PHP.
Three types of arrays are classified in PHP:
Indexed: the arrays that have a numeric index.
Associative: the arrays with named keys.
Multidimensional: the arrays that include one or more arrays.