Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Return an array with numeric keys PHP?
In PHP, you can convert an associative array to an array with numeric keys using the array_values() function. This function returns all the values from an array with numeric indexing, starting from 0.
Syntax
array_values(array $array)
Parameters
$array − The input array from which to extract values.
Return Value
Returns an indexed array containing all the values from the input array with numeric keys starting from 0.
Example
Here's how to transform an associative array into a numerically indexed array ?
<?php
$details = [
[
"id" => "10001",
"firstName" => "John",
"lastName" => "Doe"
],
[
"id" => "10002",
"firstName" => "David",
"lastName" => "Miller"
]
];
foreach ($details as $k => $v) {
$someDetails[$v['id']][] = ['LASTNAME' => $v['lastName'], 'FIRSTNAME' => $v['firstName']];
}
print_r(array_values($someDetails));
?>
The output of the above code is ?
Array
(
[0] => Array
(
[0] => Array
(
[LASTNAME] => Doe
[FIRSTNAME] => John
)
)
[1] => Array
(
[0] => Array
(
[LASTNAME] => Miller
[FIRSTNAME] => David
)
)
)
Simple Example
A basic example showing array_values() in action ?
<?php
$associativeArray = [
'name' => 'Alice',
'age' => 25,
'city' => 'New York'
];
$numericArray = array_values($associativeArray);
print_r($numericArray);
?>
Array
(
[0] => Alice
[1] => 25
[2] => New York
)
Conclusion
The array_values() function is the most efficient way to convert associative arrays to numeric-indexed arrays. It preserves the order of elements while replacing string keys with sequential numeric keys starting from 0.
