0

In my below code I got so confused. I have identified a variable in PHP then I got into a JavaScript loop and I want to increment my PHP variable with the JS loop. but what happens is that it increases only for one time and exit from the loop! below code to understand:

<?php
$ct =5 ;

?>

<script type="text/javascript">
    
for(var r=1; r<=10; r++ )
{
    <?php $ct++ ;?>

}

alert(<?php echo $ct;?>);

the alert here gives me 6!! but as much as I understand It should give me 15

MHassan
  • 25
  • 9
  • PHP runs first, then JS runs. PHP is server side. – user3783243 Jun 02 '21 at 16:45
  • You need to understand/remember that the PHP runs first (on the server, in order to create the page), and whatever output it produces then becomes a fixed value in the JavaScript, which is executed later (when the created page is delivered to the browser). So it's irrelevant how many times you loop in the JavaScript, $ct was fixed at 6 before it even started - use the View Source feature in your browser to examine the finished JavaScript source code and you'll see what I mean. But what is the point of mixing the languages here anyway? Just do the whole thing in one or the other. – ADyson Jun 02 '21 at 17:22

0 Answers0