'img srcset and sizes not working in PHP/JavaScript

I am creating dynamic HTML from PHP. I wanted to resize images for mobile, but it doesn't seem to work. It picks up the larger image on my desktop with resolution 1440x900 as expected, but on my mobile the resolution shows up as 360x640 but it still picks up the larger image whereas I want it to pick the resized image. I am not an expert so any help would be appreciated.

<script language="javascript">
alert("Your screen resolution is: " + screen.width + "x" + screen.height);
</script>

        <?php
        print "<div class=\"row\">";
            print "<div class=\"img-P\">";
                print "<img srcset=\"images/resized/$img_resized 640w, images/$img 1024w\" 
                            sizes=\"(max-width: 640px) 640px, 1024px\" 
                            src=\"images/$img\"
                            loading=\"lazy\" />";
            print "</div>";
        print "</div>";
        ?>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source