Home  >  Article  >  Backend Development  >  How to Remove and Re-index Array Elements in PHP?

How to Remove and Re-index Array Elements in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 03:40:14256browse

How to Remove and Re-index Array Elements in PHP?

Removing and Re-Indexing Array Elements

When working with arrays in PHP, it's often necessary to modify their elements. One common operation is removing an element from the array. However, after removing an element, the remaining elements may no longer be indexed as expected. This can create difficulties in maintaining the coherence of the array.

Solution

To remove an element from an array and subsequently re-index it, PHP provides a convenient solution. The unset() function can be used to delete an element from an array by its index. However, this action will not re-index the remaining elements.

To re-index the array, the array_values() function can be employed. It returns a new array that contains the original elements in a sequential order, starting from index 0.

Example

Consider the following array:

$foo = array(
    'whatever', // [0]
    'foo', // [1]
    'bar' // [2]
);

To remove the element at index 0 and re-index the array, the following steps can be taken:

unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array

The resulting $foo2 array will be as follows:

$foo2 = array(
    'foo', // [0], before [1]
    'bar' // [1], before [2]
);

As demonstrated, the element at index 0 has been removed and the remaining elements have been re-indexed starting from 0.

The above is the detailed content of How to Remove and Re-index Array Elements in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn