How can you change the value of a specific key in an array in PHP using a loop?

To change the value of a specific key in an array in PHP using a loop, you can iterate through the array using a foreach loop and check if the current key matches the key you want to change. If it does, you can update the value of that key. This approach allows you to dynamically update the value of a specific key without knowing its position in the array.

<?php
// Sample array
$array = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3');

// Key to change
$keyToChange = 'key2';

// New value for the key
$newValue = 'new value';

// Loop through the array and update the value of the specified key
foreach ($array as $key => $value) {
    if ($key === $keyToChange) {
        $array[$key] = $newValue;
        break; // Exit the loop once the key is found and updated
    }
}

// Output the updated array
print_r($array);
?>