How can arrays be used effectively in PHP for replacing variables in text?

When replacing variables in text in PHP, arrays can be used effectively by storing the variable names as keys and their corresponding values as values in the array. This allows for easy substitution of variables in the text by looping through the array and replacing the variable placeholders with their values.

// Define an array with variable names as keys and values as values
$variables = [
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York'
];

// Text with variable placeholders
$text = 'Hello, my name is {name}. I am {age} years old and I live in {city}';

// Replace variable placeholders with their values
foreach ($variables as $key => $value) {
    $text = str_replace('{' . $key . '}', $value, $text);
}

// Output the text with replaced variables
echo $text;