Home >Backend Development >PHP Tutorial >How to Re-Index an Array in PHP with `array_values()`?

How to Re-Index an Array in PHP with `array_values()`?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 02:57:30580browse

How to Re-Index an Array in PHP with `array_values()`?

How to Re-Index Array Values in PHP

Re-indexing an array to assign numeric keys starting from 0 is a common requirement in PHP programming. Consider the following array:

<code class="php">$array = [
    'id' => 3,
    'user_id' => 1,
    'clan_id' => 1,
    'date' => '2009-09-24 09:02:05',
    // ...
];</code>

To re-index this array, PHP offers the array_values() function. When applied to an array, it generates a new array that consists of the original array's values, with numeric keys starting from 0:

<code class="php">$reindexedArray = array_values($array);

// Output:
/*
Array
(
    [0] => 3
    [1] => 1
    [2] => 1
    [3] => 2009-09-24 09:02:05
    // ...
) 
*/</code>

The array_values() function is particularly useful when you need to iterate over an array sequentially and rely on the index values. By using the re-indexed array, you can avoid having to deal with unpredictable or irregular key names.

The above is the detailed content of How to Re-Index an Array in PHP with `array_values()`?. 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