PHP array_values() Function

Usage — The PHP array_values() function is used to return all the values of an array.

It has the following syntax:

PHP

array array_values ( array $array )

Here is an example of using array_values():

PHP

$person = array("Name"=>"Peter","Age"=>"21","Country"=>"USA");

print_r(array_values($person));
/* Output —
Array
(
    [0] => Peter
    [1] => 21
    [2] => USA
) */

Return Value — This function returns an indexed array of all the values in the supplied array.

PHP Version and Changelog — The array_values() function is available in PHP 4, PHP 5, PHP 7.

Relevant Functions — Other related PHP functions that you should know about are: array_keys() which returns all the keys or a subset of the keys of an array and array_combine() which creates an array by using one array for keys and another for its values.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

array

The array parameter is used to specify the input array. This is a required parameter.

Working Examples

Here are some examples of using the array_values() function:

PHP

$parents = array("name" => "Amanda", "father" => "John", "mother" => "Sally");

print_r(array_values($parents));
/* Output —
Array
(
    [0] => Amanda
    [1] => John
    [2] => Sally
) */

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according to the ‘foreach’ ordering:

    PHP

    $numbers = array( 3 => 11, 1 => 22, 2 => 33);
    $numbers[0] = 44;
    
    print_r($numbers);
    /* Output —
    Array
    (
        [3] => 11
        [1] => 22
        [2] => 33
        [0] => 44
    ) */
    
    print_r(array_values($numbers));
    /* Output —
    Array
    (
        [0] => 11
        [1] => 22
        [2] => 33
        [3] => 44
    ) */
    

    Suggested by - biziclop at vipmail dot hu

Further Reading

  1. You can read more about the PHP array_values() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top