How can the array_keys() function be utilized to collect unique keys from multiple arrays for merging purposes in PHP?
When merging multiple arrays in PHP, it is important to ensure that the keys are unique to avoid overwriting values. One way to collect unique keys from multiple arrays is by using the array_keys() function to extract all keys from each array and then merging them into a single array using array_merge().
// Sample arrays to merge
$array1 = ["key1" => "value1", "key2" => "value2"];
$array2 = ["key2" => "value3", "key3" => "value4"];
// Collect unique keys from both arrays
$keys = array_unique(array_merge(array_keys($array1), array_keys($array2)));
// Merge arrays while preserving unique keys
$mergedArray = [];
foreach ($keys as $key) {
if (array_key_exists($key, $array1)) {
$mergedArray[$key] = $array1[$key];
}
if (array_key_exists($key, $array2)) {
$mergedArray[$key] = $array2[$key];
}
}
print_r($mergedArray);