Backend Development 4 min read

Using PHP’s array_values() Function to Reindex and Convert Arrays

This article explains PHP's array_values() function, demonstrating how it returns a new array with reindexed numeric keys for both indexed and associative arrays, and highlights that the returned array is a copy, not a reference, with practical code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP’s array_values() Function to Reindex and Convert Arrays

In PHP development, arrays are a fundamental data structure and PHP offers a rich set of array handling functions; this article introduces the highly useful 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, and its usage is straightforward—simply pass the original array as the argument.

Example with a standard indexed array:

<?php
$array = array("apple", "banana", "cherry");
$newArray = array_values($array);
print_r($newArray);
?>

Running the code outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

The result shows that the keys of the new array start from 0 and the values remain unchanged, which is helpful when you need to re‑index an array or convert an associative array to an indexed one.

The function also works with associative arrays. 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
)

Here, array_values() converts the associative array into an indexed array while preserving the original values.

It is important to note that array_values() returns a new array rather than a reference to the original. Modifying the new array does not affect the original array, as shown in the following example:

<?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 do not impact the original array.

In summary, the array_values() function is a practical tool for re‑indexing arrays and converting associative arrays to indexed arrays, enhancing code readability and maintainability in PHP projects.

backendPHParrayData StructuresPHP8array_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

login 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.