How can foreach loops be optimized to correctly format arrays in PHP, based on the examples provided in the thread?

When using foreach loops to format arrays in PHP, it's important to ensure that the keys and values are accessed correctly to avoid unexpected results. To optimize foreach loops for formatting arrays, make sure to use key-value pairs properly and apply any necessary formatting within the loop.

// Example of optimizing foreach loop to correctly format arrays
$array = ['key1' => 'value1', 'key2' => 'value2'];

// Correctly format the array using foreach loop
$formattedArray = [];
foreach ($array as $key => $value) {
    $formattedArray[] = "$key: $value";
}

// Output the formatted array
print_r($formattedArray);