Master PHP’s array_values(): Reindex Arrays Easily
This article explains how PHP’s array_values() function returns a new array with sequential numeric keys, demonstrates its use with both indexed and associative arrays, and highlights that the returned array is a copy, not a reference, allowing safe modifications.
In PHP development, arrays are a common data structure, and PHP provides many functions to manipulate them. This article introduces 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 keys starting from 0. It is used by passing an array as the argument. Below is a basic example with an indexed array:
<?php
$array = array("apple", "banana", "cherry");
$newArray = array_values($array);
print_r($newArray);
?>Running this code outputs:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)The new array’s keys start from 0 while the values remain the same, which is useful for reindexing or converting associative arrays to indexed arrays. array_values() 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 conversion is handy when you need to iterate over values without caring about original keys.
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, as shown 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 )
?>Thus, array_values() is a practical function for handling both indexed and associative arrays, improving code readability and maintainability in PHP projects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
