Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript for loop, access php array variables

A small problem that I can't seem to figure out;

So I have a php array in which I want to access through 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 the 'i' in the javascript for loop since there will be the same number of variables as for loop iterations.

I have tried to read up on possible solutions to solve this but have not been able to figure it out. I have tried using the following code but came up with nothing;

$('<div class="pops"> Hello '+ <?php echo $myArray[i]; ?> +'</div>').appendTo(elements[i]);

I feel like I am running into trouble here because of the following two reasons; My syntax is probably completely wrong. The 'i' variable I am using to access the index of the array is still a javascript variable.

I am new to javascript/php so please forgive me. Thanks for any sort of help!

like image 523
Trying2LearnMath Avatar asked Jun 06 '26 15:06

Trying2LearnMath


1 Answers

Easy, convert to json and add 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>
like image 156
venca Avatar answered Jun 08 '26 05:06

venca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!