1

I have a array stored in a PHP file in which I am storing all the values.

I am trying to loop through the entire array in JavaScript. How should I do that?

The following does not work:

var index = 0;
var info = 1;

while(index<4) {
    info = <?php echo $a[?>index<?php];?>
    index++;
}
6
  • 1
    why don't you loop in php and process each iteration in javascript instead? Commented Jun 19, 2012 at 23:26
  • 2
    A PHP Array and you're trying to loop through it with JS? I'm not sure I'm following. Why? What are you trying to do? Commented Jun 19, 2012 at 23:26
  • PHP runs server side, that just won't work Commented Jun 19, 2012 at 23:27
  • There are so many related questions: stackoverflow.com/search?q=php+array+to+javascript Commented Jun 19, 2012 at 23:28
  • 1
    @Fox: JavaScript is executed in the browser, while PHP is executed on the server. You cannot mix languages like that. PHP generates some output which is sent as text to the browser and the browser interprets it as HTML and JavaScript. Commented Jun 19, 2012 at 23:29

4 Answers 4

4

You can copy array from php to JavaScript and then process it.

var array = <?php echo json_encode($a); ?>
var index = 0;
var info = 1;

while(index<4) {
    info = array[index];
    index++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Even better to use forEach.
2

I don't know what version of php you're using, but try something like this:

var info = null;
var a = <?php echo json_encode($a); ?>;

for(var index=0;index<a.length;index++) {
    info = a[index];
}

Comments

1

You need to process the PHP into Javascript first. You can use json_encode to do this.

var index = 0;
var info = 1;
var a = <?php echo json_encode($a); ?>;

while(index < 4) {
    info = a[index];
    index++;
}

Comments

0

PHP runs on the server side, before the final page is served to the client. Javascript runs on the client side (on the browser). Therefore, what you are trying to achieve won't work. What you can do is use PHP to print the javascript code dynamically.

Comments

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.