What is the best approach to convert a given array into a new array with specific key-value pairs in PHP?
To convert a given array into a new array with specific key-value pairs in PHP, you can use a combination of array_map() and array_combine(). The array_map() function can be used to iterate over the original array and apply a callback function to each element, while array_combine() can be used to create a new array with the desired key-value pairs.
<?php
// Given array
$originalArray = array("apple", "banana", "cherry");
// Define a callback function to create key-value pairs
function createKeyValuePair($item) {
return array("fruit" => $item);
}
// Use array_map() to apply the callback function to each element
$newArray = array_map("createKeyValuePair", $originalArray);
// Use array_combine() to create a new array with the desired key-value pairs
$newArray = array_combine(range(1, count($newArray)), $newArray);
// Output the new array
print_r($newArray);
?>