Master PHP’s array_values(): Reindex Arrays Easily

This article explains how PHP's array_values() function creates a new array with reindexed keys, works with both indexed and associative arrays, and demonstrates that the returned array is a copy, not a reference, through clear code examples.

php Courses
php Courses
php Courses
Master PHP’s array_values(): Reindex Arrays Easily

In PHP development, arrays are a fundamental data structure, and PHP offers many built‑in functions to manipulate them. This article introduces the array_values() function, which returns a new array containing all the values of the original array.

The array_values() function reindexes the keys of the returned array starting from 0, making it simple to use: just pass the original array as the argument.

<?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, the keys of the new array start at 0 and increase sequentially, which is useful for scenarios that require reindexing or converting an associative array to an indexed one.

The function also works with associative arrays, preserving the original values while reindexing the keys. Example:

<?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 leave the original array unchanged.

In summary, array_values() is a highly practical function for array manipulation in PHP, capable of handling both indexed and associative arrays, and helps improve code readability and maintainability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Arrayphp-functionsarray_values
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.