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()
orarray_unique()
to reset keys. - Needed when passing JSON data or using front-end APIs expecting numerical arrays.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.