need to loop through a PHP array in JavaScript

Before your ehco/print or else your php array we make sure it's in JavaScript syntax.

<?php
$s=array('a','b','c','d','e','f');
$s_to_json=json_encode((array)$s);
?>

<script type="text/javascript">

var fromPHP=<? echo $s_to_json ?>;

for (i=0; i<fromPHP.length; i++) {

yourValue=fromPHP[i];

}

</script>

<?php
$s= array('a','b','c','d','e','f') ;
?>

<?php foreach($s as $a){ ?>

document.write('<?=$a?>');

<?php } ?>

Not tested but thats one way.


Javascript and PHP cannot be combined. They are two completely different programs that communicate only vaguely. The PHP runs on the server computer and generates the HTML. The javascript runs on the client computer in the webbrowser and acts on that HTML. If you need to move information from PHP into Javscript somehow, then you have to store it in the HTML and have the Javascript access it through that HTML. If you need to do the reverse, move information from Javascript to PHP, have the Javascript call a PHP page with a query string.

One way to place the information in your array somewhere where Javascript can get to it, would be to echo it into a hidden div. Either in a series of ided spans or just a comma separated list. Then you can pull it out of the DOM.

For example:

<div style="display: none;" id="myArray">
<?php 
echo '<span id="myArray.count">'.sizeof($s).'</span>';
for ($i = 0; $i < sizeof($s); $i++) {
    echo '<span id="myArray.'.$i.'">'.$s[$i].'</span>';
}
?>
</div>

Then in the Javascript you can access the array in the DOM:

var myArray = new Array();

for(i = 0; i < document.getElementById('myArray.count').innerHTML; i++) {
  document.write(document.getElementById('myArray.'+i).innerHTML);
}

Disclaimer: untested code, and I don't have the time to perfect it right now. If someone else wants to comment or edit to fix any errors feel free :)

Tags:

Javascript

Php