html - Collapse button in Bootstrap 4 w/ PHP will open and show content but not collapse

one text

I recently attempted to use a collapse button to display content from a php query. The collapse button will show the content enclosed, but not collapse once it is opened. I troubleshooted many different possibilities that could be causing this issue, and only one gave me progress, which was putting the bootstrap JS CDN before the JQuery one. This made the collapse button work and it looked great, but it also broke a lot of my code and I got a console error warning me that Bootstrap's CDN should be after JQuery. For the record, I also attempted to move the if statement contained in the Div outside of it and use a variable instead, and it made no difference.

Here is a snipped of my code (Note that $comments is an array from php):

    echo "<head>
        <meta charset='utf-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>

        <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css' integrity='sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk' crossorigin='anonymous'>
        <link rel='stylesheet' href='styles.css'>
        <title>MelodyMate</title>
        <script src='https://code.jquery.com/jquery-3.5.1.slim.min.js' integrity='sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj' crossorigin='anonymous'></script>
        <script src='https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js' integrity='sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo' crossorigin='anonymous'></script>
        <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js' integrity='sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI' crossorigin='anonymous'></script>
    </head>
    <body>
<button type='button' class='btn btn-primary' data-toggle='collapse' data-target='#replies'>View Replies</button>
                    <div id='replies' class='collapse'>";
                    if (isset($comments)){
                        $numofcomments = count($comments);
                        $commentnum = 0;
                        while ($commentnum != $numofcomments){
                            echo $comments[$commentnum];
                            $commentnum = $commentnum+1;
                        }
                    }
        echo "
    </div>
</body>";

Source