Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

array_values()

Synopsis

    array array_values ( array arr )

The array_values() takes an array as its only parameter, and returns an array of all the values in that array. This might seem pointless, but its usefulness lies in how numerical arrays are indexed. If you use the array operator [ ] to assign variables to an array, PHP will use 0, 1, 2, etc. as the keys. If you then sort the array using a function such as asort(), which keeps the keys intact, the array's keys will be out of order because asort() sorts by value, not by key.

Using the array_values() function makes PHP create a new array where the indexes are recreated and the values are copied from the old array, essentially making it renumber the array elements. For example:

    $words = array("Hello", "World", "Foo", "Bar", "Baz");

    var_dump($words);
    // prints the array out in its original ordering, so
    // array(5) { [0]=> string(5) "Hello" [1]=> string(5)
    // "World" [2]=> string(3) "Foo" [3]=> string(3) "Bar"
    // [4]=> string(3) "Baz" }

    asort($words);

    var_dump($words);
    // ordered by the values, but the keys will be jumbled up, so
    // array(5) { [3]=> string(3) "Bar" [4]=> string(3) "Baz"
    // [2]=> string(3) "Foo" [0]=> string(5) "Hello"
    // [1]=> string(5) "World" }

    var_dump(array_values($words));
    // array_values() creates a new array, re-ordering the keys. So:
    // array(5) { [0]=> string(3) "Bar" [1]=> string(3) "Baz"
    // [2]=> string(3) "Foo" [3]=> string(5) "Hello"
    // [4]=> string(5) "World" }

You will find array_values() useful ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page