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!
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.
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With