Home >Backend Development >PHP Tutorial >How to Re-index Array Values in PHP Starting from Zero?
Re-indexing Array Values in PHP
When working with arrays in PHP, there might be situations where you need to re-index the values to start at a specific index, such as zero.
Consider the following situation:
<code class="php">$array = [ 'id' => 3, 'user_id' => 1, 'clan_id' => 1, 'date' => '2009-09-24 09:02:05', // ... additional array elements ];</code>
The array keys are strings representing the names of the values. However, if you want to rename these keys to start from zero, you can use the array_values() function.
Solution: array_values()
The array_values() function returns a new array with values re-indexed starting from zero. It preserves the values of the original array, but changes the keys to sequential integers.
<code class="php">$reindexedArray = array_values($array);</code>
The resulting array, $reindexedArray, will now have the following structure:
<code class="php">[0] => 3 [1] => 1 [2] => 1 [3] => '2009-09-24 09:02:05' // ... additional re-indexed array elements</code>
Using array_values(), you can easily re-index the values of an array in PHP, starting from a specific index if necessary.
The above is the detailed content of How to Re-index Array Values in PHP Starting from Zero?. For more information, please follow other related articles on the PHP Chinese website!