Passing PHP variables to Javascript

Discussion in 'PHP' started by enchance, Oct 15, 2009.

  1. #1
    Can anyone tell me the best way to pass a PHP array into a Javascript array? It just crossed my mind just now.

    I'm not too familiar wit JSON Or XML but here's what I have so far but it doesn't work though. What's wrong with it? :confused:
    
    var js_arr = [];
    <?php
    $tempo_arr = array('list', 'of', 'elements');
    foreach($tempo_arr as $element)
    {
    	echo "js_arr.push($element);\n";
    }
    ?>
    alert(js_arr);
    
    Code (markup):
     
    Last edited: Oct 15, 2009
    enchance, Oct 15, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You should probably do something like:

    
    echo "js_arr.push('$element');\n";
    PHP:
    Or if you have PHP 5.2+, you can just do:

    echo 'js_arr = ' . json_encode($temp_arr);
     
    premiumscripts, Oct 15, 2009 IP
  3. enchance

    enchance Peon

    Messages:
    109
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hey, it worked. Thanks!
     
    enchance, Oct 16, 2009 IP