3

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!

2 Answers 2

2

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>
1
  • Thanks. I'm actually still getting an empty myArray on return Commented Jun 19, 2015 at 18:02
0

I see two ways of doing this: One is with JSON as @venca said.

The other way is using a php loop instead.

<?
  foreach ($myArray as $elem){
    echo '<div class="pops"> Hello '.$elem.'</div>';
  }
?>

This will generate one div with class pops for each element in your php array. If you want to run some javascript code instead, you should to something like this:

<script>
<?
  int i=0;
  foreach ($myArray as $elem){
    echo '$("<div class=\"pops\"> Hello '.$elem.'</div>").appendTo(elements['.i.'])';
    i++;
  }
?>
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.