Master PHP’s array_values(): Reindex Arrays and Convert Associative to Indexed

Learn how PHP’s array_values() function returns a new array with sequential numeric keys, reindexes indexed arrays, converts associative arrays to indexed ones, and operates without affecting the original array, illustrated with clear code examples and practical use cases.

php Courses
php Courses
php Courses
Master PHP’s array_values(): Reindex Arrays and Convert Associative to Indexed

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 elements of the original array.

The array_values() function returns a new array whose keys are reindexed starting from 0. It is used by passing an array as the argument. Below is a simple example:

<?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 function is useful when you need to reindex an array or convert an associative array to an indexed array.

It also works with associative arrays, preserving the values while reindexing the keys. 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
)

Note that array_values() returns a new array, not a reference to the original. Modifying the new array does not affect the original, 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 )
?>

In summary, array_values() is a practical function for handling arrays in PHP, capable of reindexing indexed arrays and converting associative arrays while keeping the original values intact, thereby improving 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.

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