I’m trying to add an item to a PHP array. The item I’m trying to add to the array may have the same index as an item which is already in the array. How can I add the item to the array without overwriting an item that shares the same index inside the array? I’d like similar indexes to turn into a 2D array.
//Original Array
$array = array (
"item1" => "data1",
"item2" => "data2",
"item3" => "data3"
);
//Add items to array
$array["item1"] = "data2d";
$array["item5"] = "data4";
//Desired output
array (
"item1" => array("data1", "data4"),
"item2" => "data2",
"item3" => "data3",
"item4" => "data4"
);
How would I achieve the desired output?
Try a function like below. The function has not been tested so there might be some syntax errors.
Used like