Jump to content

Loop php array in javascript


somedude

Recommended Posts

IS there a way to loop through a php array in a javascript loop

<?php
$name=array("hi","bye","yo"); 
?>

<script language="JavaScript">

var xx=new Array()
var i=0
for (i=0;i<=2;i++)

{
xx="<?php echo $name["i"]; ?>";
alert(xx);
}

//}
</script>

Something like that, but obviously, i'm getting errors.

" Cannot use [] for reading in "

Link to comment
https://forums.phpfreaks.com/topic/33986-loop-php-array-in-javascript/
Share on other sites

No. PHP runs on the server while Javascript runs on the client.

What you could do though is put all the elements you want into a javascript array. Something like...

[code]
<?php
$name = array("hi","bye","yo");
?>
<script language="JavaScript">
  var arr = new Array("<?php echo implode('","',$name) ?>");
  var i = 0;
  for (i=0; i<=2; i++) {
    alert(arr[i]);
  }
</script>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.