0
<script type="text/javascript" >

var arrayjs = <?php $arrayphp = array(1,3,5,6,7,10); ?>

//each? for? with jQuery {
  console.log(num);
}

</script>

I have array in PHP. How can i get this for jQuery and showing with loop each or for?

1
  • Please search for "how to pass PHP variables to Javascript" type question on here. This is one of the most asked topics. Commented Jan 27, 2012 at 1:57

1 Answer 1

5
<script type="text/javascript">

var arrayjs = <?= json_encode(array(1,3,5,6,7,10)) ?>;

for(var i=0; i<arrayjs.length; ++i) {
    console.log(arrayjs[i]);
}

</script>

There is no foreach in JavaScript. You have to do it old-school with indexes.

To pass a PHP variable to JS, use json_encode.

Edit: You can use $.each if you're using jQuery.

Sign up to request clarification or add additional context in comments.

8 Comments

@MarkFondy: Doesn't matter. The array is still 0-indexed. The array can contain anything.
Yes, sorry, my mistake :) Thanks for help
javascript does have a forEach for arrays works in a lot browsers now.
Am I missing something? What about javascript's for (x in object) function?
@XyanEwing how can i make it? Please add new answer:)
|

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.