0

Obviously I can't use the JS var i in my PHP code. I tried breaking it off from the PHP code by putting it outside of the tags but it didn't work.

<?php
$list = array();
$list[0] = "January";
$list[1] = "February";
$list[2] = "March";
$list[3] = "April";
$list[4] = "May";
?>



<script type="text/javascript"> 
for (var i = 0; i < <?php echo sizeof($list);?>; i++) {
    alert("<?php echo $list[i];?>");
}
</script>
rvelbon
  • 91
  • 5
  • You cannot. PHP is server-side and JS is client-side. You need to echo the PHP as a JS object and then you can loop through it. But I have a *sneaking suspicion* this would only answer part of your question....the part you haven't aksed yet. – Jay Blanchard Nov 21 '16 at 22:32
  • 1
    Here: http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript , specifically part 3, json_encode() is what you're looking for. – Anees Saban Nov 21 '16 at 22:33
  • @JayBlanchard But how do I echo a PHP array as a JS object? For int and string this wouldn't be problematic... – rvelbon Nov 21 '16 at 23:25
  • @AneesSaban Part 3 does not answer my question. From my code it is clear that I already know how to echo the PHP into the JS. What I want to know is how I can pass a JS var into the php loop. – rvelbon Nov 21 '16 at 23:27
  • I appear to have misread, your js alerts confused me. Sending js vars to php has to happen via a callback to the server. What you are attempting is something else. – Anees Saban Nov 21 '16 at 23:30
  • To pass JS to PHP you wold use AJAX. – Jay Blanchard Nov 22 '16 at 12:41

0 Answers0