Using javascript for loop use php array variables
Small problem that I cannot figure out
So I have a php array that I want to access via javascript using a for loop to specify the index. For example,
<?php
$myArray = array("a", "b", "c");
?>
<script type="text/javascript">
for(var i = 0; i < elements.length; i++){
$('<div class="pops"> Hello '+ THIS IS WHERE I WANT THE PHP VARIABLES +'</div>').appendTo(elements[i]);
</script>
I would like to access the variables in $ myArray using 'i' in the javascript loop as there will be the same number of variables as there are for the loop iterations.
I tried to read about possible solutions to solve this problem but couldn't figure it out. I tried using the following code, but came up with nothing;
$('<div class="pops"> Hello '+ <?php echo $myArray[i]; ?> +'</div>').appendTo(elements[i]);
I feel that I am in trouble for the following two reasons; My syntax is probably completely wrong. The "i" variable that I use to access the array index is still a javascript variable.
I am new to javascript / php, so please forgive me. Thanks for any help!
source to share
Simple conversion to json and adding to script element.
<?php $myArray = array("a", "b", "c"); ?>
<script type="text/javascript">
// I assume phpArray length equals to elements length
var phpArray = <?php echo json_encode($myArray); ?> ;
for(var i = 0; i < elements.length; i++){
$('<div class="pops"> Hello '+ phpArray[i] +'</div>').appendTo(elements[i]);
</script>
source to share
I see two ways to do this, one with JSON as @venca said.
Another way is to use php loop.
<?
foreach ($myArray as $elem){
echo '<div class="pops"> Hello '.$elem.'</div>';
}
?>
This will generate one div using the pops class for each element in your php array. If you want to run javascript code instead, you should do something like this:
<script>
<?
int i=0;
foreach ($myArray as $elem){
echo '$("<div class=\"pops\"> Hello '.$elem.'</div>").appendTo(elements['.i.'])';
i++;
}
?>
</script>
source to share