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?
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:Demo