Reindexing an Array
In PHP, arrays are dynamically indexed. This means that the keys of an array can be any arbitrary value, and they do not have to follow any specific pattern. However, there are times when you may want to reindex an array, such as when you need to reset the keys to a continuous sequence of numbers starting from 0.
Problem:
Consider the following array:
array( 0 => 'val', 2 => 'val', 3 => 'val', 5 => 'val', 7 => 'val' );
How can you reindex this array so that the keys go like 0, 1, 2, 3, 4?
Solution:
To reindex an array, you can use the array_values() function. This function takes an array as an input and returns a new array with the same values as the input array, but with the keys reindexed to start from 0.
$reindexed_array = array_values($old_array);
In this example, $reindexed_array will be as follows:
array( 0 => 'val', 1 => 'val', 2 => 'val', 3 => 'val', 4 => 'val' );
The above is the detailed content of How Do I Reindex a PHP Array to Start from 0?. For more information, please follow other related articles on the PHP Chinese website!