Create a new index array from an associative array
Here is an example of how you can create a new index array from an associative array in PHP:
$associativeArray = array(
'name' => 'John',
'age' => 30,
'city' => 'New York'
);
$indexArray = array_values($associativeArray);
print_r($indexArray);
This will output:
Array
(
[0] => name
[1] => age
[2] => city
)
The array_values()
function returns a new array with the same values as the original array, but with numeric keys starting from 0.
Alternatively, you can use a loop to create the index array:
$associativeArray = array(
'name' => 'John',
'age' => 30,
'city' => 'New York'
);
$indexArray = array();
foreach ($associativeArray as $key => $value) {
$indexArray[] = $key;
}
print_r($indexArray);
This will also output:
Array
(
[0] => name
[1] => age
[2] => city
)
Note that the array_values()
function is more concise and efficient, but the loop approach can be useful if you need to perform additional operations on the keys or values.