Using PHP's array_values() Function to Reindex Arrays
This article explains PHP's array_values() function, showing how it returns a new array with sequential numeric keys for both indexed and associative arrays, includes practical code examples, demonstrates that the returned array is a copy, and discusses typical use cases.
In PHP development, arrays are a fundamental data structure, and PHP provides many built‑in functions to manipulate them; this article focuses on the 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 consecutively; it requires only the original array as its argument.
<code><?php
$array = array("apple", "banana", "cherry");
$newArray = array_values($array);
print_r($newArray);
?></code>Running the code above outputs:
<code>Array
(
[0] => apple
[1] => banana
[2] => cherry
)</code>The function also works with associative arrays, converting them to indexed arrays while preserving the original values:
<code><?php
$student = array(
"name" => "张三",
"age" => 18,
"score" => 95
);
$newArray = array_values($student);
print_r($newArray);
?></code>The result is:
<code>Array
(
[0] => 张三
[1] => 18
[2] => 95
)</code>It is important to note that array_values() returns a new array rather than a reference; modifying the new array does not affect the original one:
<code><?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 )
?></code>Thus, array_values() is a practical function for reindexing arrays, converting associative arrays to indexed ones, and ensuring that the original data remains unchanged, which can improve code readability and maintainability in PHP projects.
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.