View Full Version : Use javascript variable to increment php array

07-18-2012, 11:15 PM
I am in need of incrementing through a php array with the javascript variable "i" instead of where i have 0 in the $members array call

var i = 0;
while (i<5)
if (<?php echo json_encode($members[0]['department']); ?> == "CHE"){
contacts.push({"NAME":"Sir Saula","TITLE":"John","CONTACT":"bab","RESEARCH":"Ph.D."});


07-18-2012, 11:24 PM
How about looping in PHP (inside <script type="text/javascript"> tags) instead of JavaScript, and include JS code as needed?

Then, again.. this is not tested, but..

if (<?php echo json_encode($members[?>i<?php]['department']); ?> == "CHE"){

Old Pedant
07-18-2012, 11:24 PM
You can't.

PHP code can *NOT* see any JavaScript variables. Period.

The only ways to send a javascript variable (or any client-side value) to PHP are:
-- post a <form>
-- use a querystring with a php URL
-- use AJAX

07-19-2012, 01:47 AM
The only way you can really do that is to have php rewrite the array in javascript, and then let javascript use it. The best way to do that is have javascript declare an array and then write code for php to use javascript 'push' to add elements to the array, because it prevents confusion in the case of mixed data types.
myarray =[];
loop over this;
echo 'myarray.push('.$data[i].');';