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, we have gathered helpful approaches that will help to achieve that.

Knowledge in CSS

Using unset() and array_values()

Watch a course Learn object oriented PHP

In this section, we will proceed with removing an array element with the unset() function and, then, reindexing it with array_values().

The unset() function is used for unsetting a given variable.

The syntax is the following:

unset(mixed $var, mixed ...$vars): void

The array_values() function is aimed at returning all the values from the array and numerically indexing the array.

The syntax is the following:

array array_values ( array $array )

Now, let’s see how these two functions look like in action:

<?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);
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 array_splice() 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:

array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] ) : array

For a better perception of how this function works, check out the example below:

<?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 array() function or [] 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.