The array_values()
function in PHP is used to return all the values from an array and reindexes the array numerically from zero.
🔹 Syntax:
array_values(array $array): array
🔹 Purpose:
- It removes the original keys (whether associative or not) and reindexes the array starting from
0
.
🔹 Example 1: Basic Associative Array
<?php
$person = [
"name" => "Alice",
"age" => 25,
"city" => "New York"
];
$values = array_values($person);
print_r($values);
?>
Output:
Array
(
[0] => Alice
[1] => 25
[2] => New York
)
✅ The keys are removed, and values are reindexed from 0.
🔹 Example 2: Indexed Array with Skipped Indexes
<?php
$numbers = [
3 => 10,
7 => 20,
9 => 30
];
$newArray = array_values($numbers);
print_r($newArray);
?>
Output:
Array
(
[0] => 10
[1] => 20
[2] => 30
)
✅ Even though the original array had keys 3, 7, and 9, array_values()
reindexes them as 0, 1, 2.
🔹 Example 3: Mixed Keys
<?php
$data = [
"a" => "Apple",
1 => "Banana",
"b" => "Cherry"
];
$values = array_values($data);
print_r($values);
?>
Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
)
✅ Use Cases:
- When you want a clean indexed array of values only.
- Useful after using
array_filter()
or array_unique()
to reset keys.
- Needed when passing JSON data or using front-end APIs expecting numerical arrays.