Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a bunch of parallel arrays in php

$phoneNums = array();
$minutesUsed = array();
$plans = array();
$charges = array();

and I'm trying to put them in arrays in JS so I can access them and print values into the page

var phoneNums = <?php echo $phoneNums ?>;
var minutesUsed = <?php echo $minutesUsed ?>;
var plans = <?php echo $plans ?>;
var charge = <?php echo $charges ?>;

What ends up happening is my values end up as undefined. How would I pass an array from php to js this without using AJAX or JQuery?

share|improve this question
add comment (requires an account with 50 reputation)

1 Answer

up vote 3 down vote accepted

Echoing a PHP array will not print its contents. Even if it would, it would not be in the same format that Javascript expects ([1,2,3]) - also, associative arrays in PHP work quite differently than JS, where they are objects ({'x':1,'y':2}).

JSON is Javascript Object Notation. If you encode your data in JSON (in PHP, you can use json_encode() to do that), it will be absolutely acceptable for Javascript, so you can simply print it:

var phoneNums = <?php echo json_encode($phoneNums); ?>;

Demo

share|improve this answer
Uncaught Syntax Error: Unexpected end of input. – ArcaneExplosion May 6 '12 at 21:06
@ArcaneExplosion My mistake, check now. – bažmegakapa May 6 '12 at 21:06
hmm this time nothing prints out unlike before where it was just undefined. and it comes up as an empty array in the error console – ArcaneExplosion May 6 '12 at 21:12
@ArcaneExplosion I have added a Demo that shows it working. Are you sure you have an array with that name in that variable scope? – bažmegakapa May 6 '12 at 21:13
1  
I left out the parts where i populated the array. I figured out the issue was my JS ran before the function call to populate the arrays. My mistake – ArcaneExplosion May 6 '12 at 21:20
show 2 more commentsadd comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.