I’m trying to implement a javascript for loop in which a php variable is counting (phpVar++) each loop. However, the variable, which starts at 0, always ends up being 1, even though the loop loops multiple times.
Is this not possible?
<script>
<?php $totalMarkers=0; ?>
for (var i = 0; i < markers.length; i++) {
<?php $totalMarkers=$totalMarkers+1; ?>
}
<?php echo $totalMarkers ?> //this always prints "1"
</script>
I’m trying to do this so that I can print $totalMarkers in different places in the Body of the HTML.
Javascript is executed on the client computer, PHP is executed on the server. So, your loop does not run until the page is completely loaded in the user’s browser — at that point, no PHP will be executed.
When that page is rendered, this is the process:
<script><– gets output literally<?php $totalMarkers=0; ?><– has no outputfor (var i = 0; i < markers.length; i++) {<– is output literally<?php $totalMarkers=$totalMarkers+1; ?><– has no output}< — is output literally<?php echo $totalMarkers ?><– outputs 1</script><– is output literallyIf you were to view source, you would see this: