PHP array_values Function
last modified March 13, 2025
The PHP array_values function returns all values from an array
and indexes the array numerically. It's useful for reindexing arrays.
Basic Definition
The array_values function extracts all values from an array.
It returns a new array with sequential numeric keys starting from 0.
Syntax: array_values(array $array): array. The function
preserves the order of values but resets all keys to numeric indices.
Basic array_values Example
This shows how to extract values from an associative array with string keys.
<?php
$user = [
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 30
];
$values = array_values($user);
print_r($values);
This extracts all values from the associative array. The output will be:
['John Doe', 'john@example.com', 30] with numeric indices.
Reindexing an Array
Use array_values to reset numeric keys after unset operations.
<?php $numbers = [10 => 'a', 20 => 'b', 30 => 'c']; unset($numbers[20]); $reindexed = array_values($numbers); print_r($reindexed);
After removing element 'b', the array has gaps. array_values
creates a new array with sequential keys: [0 => 'a', 1 => 'c'].
Working with Mixed Arrays
array_values works with arrays containing different value types.
<?php
$mixed = [
'a' => 'apple',
5 => 3.14,
'test' => true,
null
];
$values = array_values($mixed);
print_r($values);
The function preserves all values regardless of type. The output contains:
['apple', 3.14, true, null] with new numeric indices.
Preserving Order with array_values
The function maintains the original order of elements in the array.
<?php
$unordered = [
10 => 'ten',
2 => 'two',
5 => 'five'
];
$ordered = array_values($unordered);
print_r($ordered);
Despite the original non-sequential keys, the values keep their order:
['ten', 'two', 'five']. Only the indices become sequential.
Combining with Other Functions
array_values can be combined with functions like array_unique.
<?php $duplicates = ['a', 'b', 'a', 'c', 'b', 'd']; $unique = array_values(array_unique($duplicates)); print_r($unique);
This removes duplicates and reindexes the array. The result is:
[0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'].
Best Practices
- Memory Usage: Creates new array, consider memory for large arrays.
- Key Preservation: Use only when keys don't matter.
- Performance: Generally efficient for most use cases.
- Readability: Makes code clearer when only values are needed.
Source
PHP array_values Documentation
This tutorial covered the PHP array_values function with practical
examples showing its usage for array manipulation scenarios.
Author
List all PHP Array Functions.