Fox
Fox

Reputation: 9444

How do I retrieve values from a PHP array?

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++;
}

Upvotes: 1

Views: 120

Answers (4)

&#193;lvaro
&#193;lvaro

Reputation: 269

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.

Upvotes: 0

somedev
somedev

Reputation: 1053

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];
}

Upvotes: 2

kingcoyote
kingcoyote

Reputation: 1146

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++;
}

Upvotes: 1

jcubic
jcubic

Reputation: 66490

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++;
}

Upvotes: 4

Related Questions