Using PHP’s array_values() Function to Reindex Arrays
This article explains how the PHP array_values() function returns a new array with sequential numeric keys, demonstrates its usage with both indexed and associative arrays, and highlights that the returned array is a copy, not a reference to the original.
In PHP development, arrays are a fundamental data structure, and PHP provides many built‑in functions to manipulate them. This article introduces the very useful array_values() function, which returns a new array containing all the values of the original array.
The array_values() function reindexes the array so that the keys start from 0 and increase sequentially. It requires only the original array as its argument. Below is a simple example with an indexed array:
<?php
$array = array("apple", "banana", "cherry");
$newArray = array_values($array);
print_r($newArray);
?>Running the code above outputs:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)As shown, array_values() returns a new array whose keys start at 0 while preserving the original values, which is handy when you need to re‑index an array or convert an associative array to an indexed one.
The function also works with associative arrays. It discards the original keys and returns a numerically indexed array of the values. Example:
<?php
$student = array(
"name" => "张三",
"age" => 18,
"score" => 95
);
$newArray = array_values($student);
print_r($newArray);
?>The output is:
Array
(
[0] => 张三
[1] => 18
[2] => 95
)This demonstrates that array_values() converts an associative array into an indexed array while keeping the original values, which is useful for looping or other operations that require numeric keys.
It is important to note that the array returned by array_values() is a copy, not a reference to the original array. Modifying the new array does not affect the original one, as illustrated below:
<?php
$array = array("apple", "banana", "cherry");
$newArray = array_values($array);
$newArray[0] = "orange";
print_r($newArray); // Array ( [0] => orange [1] => banana [2] => cherry )
print_r($array); // Array ( [0] => apple [1] => banana [2] => cherry )
?>From this example you can see that changing the first element of the new array leaves the original array unchanged.
In summary, the array_values() function is a practical tool for handling arrays in PHP. It returns a new array with all values, works with both indexed and associative arrays, and helps improve code readability and maintainability in various development scenarios.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.