Using PHP's array_values() Function to Reindex and Convert Arrays
This article explains PHP's array_values() function, showing how it returns a new array with re‑indexed keys, provides examples with both indexed and associative arrays, demonstrates that the returned array is a copy, and discusses practical scenarios for its use.
In PHP development, arrays are a fundamental data structure, and PHP offers a rich set of functions for array manipulation. This article introduces the array_values() function, which returns a new array containing all the values of the original array with keys re‑indexed starting from 0.
The function is straightforward: pass any array as the argument, and it returns a copy where the keys are reset. This is useful for re‑indexing numeric arrays or converting associative arrays into simple indexed arrays.
Example with a regular indexed array:
<?php
$array = array("apple", "banana", "cherry");
$newArray = array_values($array);
print_r($newArray);
?>Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)Example with an associative array:
<?php
$student = array(
"name" => "张三",
"age" => 18,
"score" => 95
);
$newArray = array_values($student);
print_r($newArray);
?>Output:
Array
(
[0] => 张三
[1] => 18
[2] => 95
)Note that array_values() returns a new array, not a reference to the original. Modifying the new array does not affect the original array:
<?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 )
?>This demonstrates that changes to the returned array are isolated from the source array.
In summary, array_values() is a practical function for resetting array keys and converting associative arrays to indexed arrays, helping improve code readability and maintainability in PHP projects.
Additional resources: Java learning materials , C language learning materials , Frontend learning materials , and other programming resources.
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.