How to Re-index Array Values in PHP Starting from Zero?

Mary-Kate Olsen
Release: 2024-10-31 22:26:02
Original
451 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!