PHP array_values: how to use in PHP with examples

PHP array_values: Detailed Guide

Description – PHP array_values

PHP array_values function returns all the values of an array.

Function Signature

array_values(array $array): array

Arguments

  • array – The input array

Return Type – PHP array_value

The function returns an array of values.

Note

PHP array_values function indexes the resulting array numerically. So, it doesn’t preserve the actual key values.

Introduction

PHP has a wide range of functions, including those dealing with the PHP associative array. PHP associative array is a hash map like data structure, keeping key and value pairs. The array is indexed on these keys to fetch the values. PHP gives us two important functions to separate the keys and values of an array.

PHP array_values

The array_keys function in PHP returns all the keys of an associative array. A counterpart of this function is array_values, except that it returns all the values of an array. In this article, we’ll see the array_values in PHP. If you’re not familiar with this function, stay with us till the end, and by the end of this article, you’ll be all set to use this function in your development.

Usage Example#1

Here is an example of the PHP array_values function.

<?php
$items = ["Fruit"=>"Apple","Vegetable"=>"Carrot","Dairy"=>"Cheese"];
 
print_r(array_values($items));
 
/*
OUTPUT
Array
(
    [0] => Apple
    [1] => Carrot
    [2] => Cheese
)
 
*/
?>

Voila! The array_values function returns an array with the values from the items array. Also, it reindexes the array numerically. An equivalent of this example could be.

<?php
$items = ["Fruit"=>"Apple","Vegetable"=>"Carrot","Dairy"=>"Cheese"];
 
$out = array();
foreach($items as $keys=>$values) {
    array_push($out,$values);
}
print_r($out);
 
/*
OUTPUT
Array
(
    [0] => Apple
    [1] => Carrot
    [2] => Cheese
)
 
*/
?>

The foreach loop keeps a reference to both keys and values. So, we can access both using the foreach loop. The PHP array_values is a short one-liner, keeps your code cleaner and more concise. 

Important Caveat

The most crucial caveat related to this function is how it works behind the scenes. The PHP array_values function reindexes the array numerically. However, it does so indirectly by creating an intermediate array rather than directly indexing it.

So, if you have an array that takes up to 8MB out of 15MB of the memory, then calling the array_values will quickly overflow the memory causing the program to halt. 

Values of PHP multidimensional arrays

We have seen a reasonably simple array in the example above. Let’s check out a more messy and complex multidimensional array.

$arr = array(
    'One' => '1',
    'MoreThan1' => array(
        'Two' => '2',
        'Three' => '3',
        'MoreThan3' => array(
            'Four' => '4',
        )
    ),
    'Morethan4' => array(
        'Five' => '5',
    ),
    'Six' => '6',
);

Here’s the output if we plug this array in the array_values in PHP.

Array
(
    [0] => 1
    [1] => Array
        (
            [Two] => 2
            [Three] => 3
            [MoreThan3] => Array
                (
                    [Four] => 4
                )
 
        )
 
    [2] => Array
        (
            [Five] => 5
        )
 
    [3] => 6
)

Oops! No change at all. All we can see is that it has reindexed the array numerically. So, what’s the workaround then?

So, a workaround is to define a function that recursively goes through the array and gets the values that are not arrays. Here’s how it works.

function array_values_recursive($arr, &$out){
   
    foreach($arr as $k=>$v) {
        if(gettype($v) == 'array') {
            array_values_recursive($v, $out);
        }
        else {
            array_push($out,$v);
        }
       
    }
 
    return $out;
}
$out= [];
print_r(array_values_recursive($arr, $out ));
 
 
/*
OUTPUT
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
*/

Awesome! Don’t worry if the example seems daunting. All it does is get each element and see if it is an array. If yes, then go through it else, append it to the output array. This logic is done recursively from the top level array all the way to the innermost array.

PHP array_column for array values

There’s yet another useful function to get a column of values from an array, PHP array_column. This description will sound vague. So, let’s see that through an example.

<?php
$names = array(
    array(
        'first_name' => 'Adam',
        'last_name' => 'Smith',
    ),
    array(
        'first_name' => 'Karl',
        'last_name' => 'Marx',
    ),
    array(      
        'first_name' => 'James',
        'last_name' => 'Bond',
    ),
    array(
        'first_name' => 'Thomas',
        'last_name' => 'Adison',
    )
);
 
print_r(array_column($names,'last_name'));
 
/*
OUTPUT
Array
(
    [0] => Smith
    [1] => Marx
    [2] => Bond
    [3] => Adison
)
*/
?>

Excellent! It gets all the last names from the array. If we visualize the array as a table, then the last name would be a column. So, this function is pretty valuable for handling organized data in PHP. Especially the data queried from a database.

Conclusion

That’s all, folks. We have seen PHP array_values function with examples and briefly discussed its working behind the scene. Besides, we found a way out for extracting values from a multidimensional array. In the end, we tried the PHP array_column function to last names from the names array. We hope you’ve learned something valuable today. Stay tuned for more exciting and informative PHP articles and tutorials.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to merge 2 arrays with the same keys in PHP

What is the difference between in_array and array_search

PHP array_search: How to use in PHP with examples


© 2022 Confident.Systems

Upcoming Live: DevOps Delivering ROI
Learn More