October 2005
Intermediate to advanced
372 pages
11h 35m
English
array_values()
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 ...