How can a loop be utilized to improve the replacement of numbers with img tags in the PHP code?

To improve the replacement of numbers with img tags in PHP code, a loop can be utilized to iterate through the numbers and replace them with the corresponding img tag. This can be achieved by creating an array of numbers and their corresponding image paths, then using a loop to search for each number in the array and replace it with the img tag.

<?php
// Array of numbers and corresponding image paths
$number_images = array(
    1 => 'img/1.jpg',
    2 => 'img/2.jpg',
    3 => 'img/3.jpg'
);

// Sample text with numbers to replace
$text = "This is a sample text with numbers 1, 2, and 3.";

// Loop through the number_images array and replace numbers with img tags
foreach($number_images as $number => $img_path) {
    $text = str_replace($number, '<img src="' . $img_path . '">', $text);
}

echo $text;
?>