How to Use array_values in PHP: Syntax and Examples
The
array_values function in PHP returns all the values from an array and reindexes them with numeric keys starting from 0. It is useful when you want to reset keys after filtering or modifying an array.Syntax
The array_values function takes one parameter, the input array, and returns a new array with numeric keys starting from 0.
array_values(array $array): array
This means it extracts all values and discards the original keys.
php
<?php $newArray = array_values($originalArray); ?>
Example
This example shows how array_values resets keys after filtering an array.
php
<?php $fruits = ["a" => "apple", "b" => "banana", "c" => "cherry"]; // Remove the element with key 'b' unset($fruits["b"]); // $fruits now has keys 'a' and 'c' print_r($fruits); // Use array_values to reindex keys $reindexed = array_values($fruits); print_r($reindexed); ?>
Output
Array
(
[a] => apple
[c] => cherry
)
Array
(
[0] => apple
[1] => cherry
)
Common Pitfalls
One common mistake is expecting array_values to preserve keys. It always resets keys to numeric indexes starting at 0. Also, it only works on arrays; passing other types will cause errors.
Another pitfall is using it unnecessarily on already indexed arrays, which wastes processing.
php
<?php // Wrong: expecting keys to stay the same $input = ["x" => 10, "y" => 20]; $output = array_values($input); print_r($output); // keys are 0 and 1, not 'x' and 'y' // Right: use when you want numeric keys $filtered = array_filter($input, fn($v) => $v > 10); $reindexed = array_values($filtered); print_r($reindexed); ?>
Output
Array
(
[0] => 10
[1] => 20
)
Array
(
[0] => 20
)
Quick Reference
| Function | Description |
|---|---|
| array_values($array) | Returns all values from $array with numeric keys starting at 0 |
| Input | Any PHP array |
| Output | New array with values and reset numeric keys |
| Use case | Reindex array after filtering or key changes |
Key Takeaways
array_values returns a new array with numeric keys starting from 0.
It is useful to reset keys after removing or filtering elements.
Original keys are discarded; keys are always reset to numbers.
Only use array_values on arrays to avoid errors.
Avoid using array_values unnecessarily on already indexed arrays.