What are some common pitfalls to avoid when working with arrays in PHP, especially when combining values from different arrays?

One common pitfall when working with arrays in PHP, especially when combining values from different arrays, is not checking if the keys exist before accessing them. This can lead to errors or unexpected behavior if a key is missing in one of the arrays. To avoid this, always check if the keys exist using isset() or array_key_exists() before accessing them.

$array1 = ['a' => 1, 'b' => 2];
$array2 = ['a' => 3, 'c' => 4];

$result = [];

foreach ($array1 as $key => $value) {
    if (isset($array2[$key])) {
        $result[$key] = $value + $array2[$key];
    } else {
        $result[$key] = $value;
    }
}

foreach ($array2 as $key => $value) {
    if (!isset($array1[$key])) {
        $result[$key] = $value;
    }
}

print_r($result);