PHP Reference ยท Array Functions
PHP array_values() function
Reference for PHP array_values(): return all values of an array as a re-indexed list, a common fix after unset(), array_filter() and sorting.
The array_values() function returns all the values of an array in order, indexed from 0. It throws away the original keys, string and integer alike. The input array is not changed.
Its most common use is re-indexing: after unset() or array_filter() leave gaps in the keys, wrapping the result in array_values() gives you a proper list again, which also matters for json_encode() (a list becomes a JSON array, an array with gaps becomes an object).
$a = [3 => "x", 7 => "y"]; print_r(array_values($a)); // [0 => "x", 1 => "y"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_values(array $array): array
| Name | Description |
|---|---|
$array |
The array to read. |
Return value: a new list containing the values of $array in their original order.
Errors / Exceptions: a TypeError if the argument is not an array.
Usage notes
- Use it to restore a list after
unset(),array_filter(),array_unique()orarray_diff(), all of which preserve the original keys. json_encode()depends on it. Only arrays with keys exactly 0, 1, 2 ... become JSON arrays.- Some functions already re-index:
array_merge()andarray_slice()renumber integer keys.array_map()with one array keeps its keys, so do not assume. - Not a sort. Order is unchanged; use
sort()orusort()to reorder. - Strings keys are dropped, so you lose information. Use
array_keys()first if you need them. - Memory: it builds a new array. If the array is already a packed list, a copy is not needed and you can skip the call.
- Objects: for plain data objects use
get_object_vars()or a cast first;array_values()accepts only arrays.