What are the best practices for creating a new array where the id serves as the key and other values as the values in PHP?
When creating a new array where the id serves as the key and other values as the values in PHP, the best practice is to loop through the original array and assign the id as the key and the other values as the values in the new array. This ensures that each item in the original array is properly mapped to its corresponding id in the new array.
$originalArray = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 3, 'name' => 'Charlie']
];
$newArray = [];
foreach ($originalArray as $item) {
$newArray[$item['id']] = $item['name'];
}
print_r($newArray);