Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to loop through a PHP array in JavaScript

Tags:

javascript

php

For example I have a PHP array, such as this one

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

And I need to loop through it in JavaScript, any ideas how do I do that?

for ( i=0 ; i < <?php echo sizeof($s) ?> ; i++) {
document.write('<?php echo $s [somehow need to get the 'i' value into here] ?>');
}

Any suggestions? Thanks!

like image 286
Roger Travis Avatar asked Apr 18 '10 18:04

Roger Travis


People also ask

Can you loop through an array in JavaScript?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array.

Can we use for loop for array in PHP?

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


1 Answers

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>
like image 161
Z. Zlatev Avatar answered Sep 22 '22 09:09

Z. Zlatev