Definition and Usage
- PHP Version
- 4+
The array_values()
function returns a new array containing all the values from the given array.
The returned array uses consecutive numeric indexes starting from 0
, and the original keys are ignored.
This function is primarily used with associative arrays and is commonly applied when:
(1). You need to ignore the original array keys and work only with the values, or
(2). You want to return all values while preserving the array's order.
Features
- Gets all values from the array.
- Ignores the original array keys entirely.
- Creates a new array consisting of the extracted values.
- The new array automatically reindexes the values with consecutive numeric indexes starting from
0
. - The original array remains unchanged.
Basic Example
/** Associative array **/
$assoc = ['name' => 'Alice', 'age' => 25];
// Get a list of all values
$values = array_values($assoc);
var_dump($values);
// Output: array(2) { [0]=> string(5) "Alice" [1]=> int(25) }
/** Indexed array **/
$indexed = ['apple', 'banana', 'cherry'];
// Using array_values() on an indexed array gives the same result
// because it already has consecutive numeric indexes starting from 0
$values_indexed = array_values($indexed);
var_dump($values_indexed);
// Output: array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(6) "cherry" }
// Note: array_values() does not modify the original array.
As shown in the example above, the array_values()
function is mainly used when you want to discard the keys of an associative array and work only with the values. It is rarely used on arrays that already have consecutive numeric indexes starting from 0
.
Syntax
array_values(array $array): array
Parameters
$array |
The array from which to extract values. |
---|
Return Values
Returns a new array containing all the values from the original array.
The returned array is indexed numerically starting from 0
.
array_values()
/** Associative array **/
$array_1 = [
0 => 100,
'color' => 'green'
];
print_r(array_values($array_1));
// Output: Array ( [0] => 100 [1] => green )
/** Multidimensional array **/
$array_2 = [
'color' => ['red', 'green', 'blue'],
'size' => ['small', 'medium', 'large']
];
print_r(array_values($array_2));
/*
Output:
Array
(
[0] => Array ( [0] => red [1] => green [2] => blue )
[1] => Array ( [0] => small [1] => medium [2] => large )
)
*/
/** Empty array **/
$array_3 = [];
print_r(array_values($array_3));
// Output: Array ( )
Practical Example
The array_values()
function can be useful in situations like the following:
- When you need to ignore the array keys and work only with the values
- When you want to return all values while preserving the array's order
Ignoring Original Array Keys and Using Only Values
Scenario: Suppose you are writing a PHP script to process orders for an online store. Each order is stored as an associative array in the following format:
// Order information
$order1 = [
'order_id' => 101,
'customer_name' => 'Alice',
'total_amount' => 50
];
$order2 = [
'order_id' => 102,
'customer_name' => "Bob",
'total_amount' => 75
];
// More orders...
To process these orders, we can use the array_values()
function. The example below converts each order into a sequential array and calculates the total order amount.
// Order information
$order1 = [
'order_id' => 101,
'customer_name' => 'Alice',
'total_amount' => 50
];
$order2 = [
'order_id' => 102,
'customer_name' => "Bob",
'total_amount' => 75
];
// Store orders in an array
$orders = array($order1, $order2);
// Calculate the total order amount
$totalAmount = 0;
foreach ($orders as $order) {
// Extract values using array_values()
$orderValues = array_values($order);
// Use the index for the total amount
$totalAmount += $orderValues[2];
}
// Display the total order amount
echo 'Total Order Amount: $' . number_format($totalAmount); // Output: 'Total Order Amount: $125'
In this code, the array_values()
function is used to extract values from each order. The total amount is retrieved from a fixed position in the array (index 2) and accumulated. This demonstrates using the function when you want to ignore the original keys and work only with the values.
The program works in the following steps:
- Define order information: Each order is defined as an associative array containing the order ID, customer name, and total amount.
- Create an array of orders: All orders are stored in an array called
$orders
. - Calculate total amount: Use a
foreach()
loop to iterate through the orders. Usearray_values()
to extract values for each order, then sum the total amounts. - Display results: The total order amount is printed, formatted using
number_format()
for readability.
Returning All Values While Preserving Array Orde
Scenario: Suppose you have an associative array of members, and you want to print the member names while preserving the array's order. The array_values()
function can help.
// Create an associative array of members
$members = [
101 => 'Alice',
102 => "Bob",
103 => "Carol"
];
// Print member names while preserving order
$memberNames = array_values($members);
foreach ($memberNames as $name) {
echo 'Member Name: ' . $name . '<br>';
}
/*
Output:
Member Name: Alice
Member Name: Bob
Member Name: Carol
*/
These two examples demonstrate practical uses of the array_values()
function. Whether to use it depends on the specific scenario.
References
See also
- PHP array_keys() Function – Get a List of Array Keys
- PHP foreach Loop
- PHP in_array() Function – Check if a Value Exists in an Array
- PHP array_map() Function – Concepts and Practical Examples
- PHP array_filter() Function – Filter Elements with a Callback
- PHP array_key_exists() Function – Check if a Key Exists in an Array
- PHP array_search() Function – Searching for a Value in an Array
- PHP array_reduce() Function – Reducing an Array to a Single Value