What best practices should be followed when integrating JavaScript functions for image swapping in a PHP environment?

When integrating JavaScript functions for image swapping in a PHP environment, it is important to ensure that the JavaScript code is properly included within the PHP file and that the image sources are dynamically generated using PHP variables. This can be achieved by echoing out the JavaScript code within the PHP file and passing the image sources as parameters to the JavaScript function.

<?php
$image1 = "image1.jpg";
$image2 = "image2.jpg";
?>

<!DOCTYPE html>
<html>
<head>
    <script>
        function swapImage(imageSrc) {
            document.getElementById('image').src = imageSrc;
        }
    </script>
</head>
<body>
    <img id="image" src="<?php echo $image1; ?>" alt="Image 1">
    <button onclick="swapImage('<?php echo $image2; ?>')">Swap Image</button>
</body>
</html>