Understanding PHP's array_values() Function: Syntax, Usage, and Examples

This article explains PHP's array_values() function, detailing its syntax, how it reindexes array values, and provides practical examples for associative, indexed, and multidimensional arrays, demonstrating its usefulness in extracting and handling array data in backend development.

php Courses
php Courses
php Courses
Understanding PHP's array_values() Function: Syntax, Usage, and Examples

PHP's array_values() function returns a new array containing all the values from the input array, reindexing them numerically.

The basic syntax is array_values(array), where array is the source array.

Basic usage with an associative array:

<?php
$students = array(
    "John" => 20,
    "Jane" => 21,
    "Tom" => 19,
    "Sarah" => 18
);
$ages = array_values($students);
print_r($ages);
?>

The output is:

Array
(
    [0] => 20
    [1] => 21
    [2] => 19
    [3] => 18
)

When applied to an indexed array, the function returns a copy with the same order:

<?php
$fruits = array("Apple", "Banana", "Orange", "Grapes");
$newArray = array_values($fruits);
print_r($newArray);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Orange
    [3] => Grapes
)

For multidimensional arrays, array_values() extracts the first level values, producing a one‑dimensional array of sub‑arrays:

<?php
$students = array(
    array("John", 20),
    array("Jane", 21),
    array("Tom", 19),
    array("Sarah", 18)
);
$values = array_values($students);
print_r($values);
?>

Result:

Array
(
    [0] => Array
        (
            [0] => John
            [1] => 20
        )
    [1] => Array
        (
            [0] => Jane
            [1] => 21
        )
    [2] => Array
        (
            [0] => Tom
            [1] => 19
        )
    [3] => Array
        (
            [0] => Sarah
            [1] => 18
        )
)

In summary, array_values() is a useful PHP utility for extracting values from associative, indexed, or multidimensional arrays and obtaining a reindexed array for further processing.

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.

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