Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2006
    Posts
    216
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Php array into a javascript array

    Hello,

    I have php array and I need to transfer this array into a javascript array. Does anyone have any code as an example of how this is done??

    thanks

  • #2
    Regular Coder
    Join Date
    May 2005
    Posts
    563
    Thanks
    0
    Thanked 3 Times in 3 Posts
    PHP Code:
    <script language="Javascript">
    var phparray = array(<?php echo implode(',',$array); ?>);
    </script>
    Try that.

    If you need to keep key values use this

    PHP Code:
    <script language="Javascript">
    var phparray = array();

    <?php
    foreach($array as $key => $value) {
    echo 
    "phparray[".$key."] = '".$value."';
    "
    ;
    }
    </script>

  • #3
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    with php 5.2 (or with the extension installed in earlier versions):
    PHP Code:
    $array=array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

    echo 
    json_encode($array);
    //output: {"a":1,"b":2,"c":3,"d":4,"e":5} 
    http://php.net/json-encode


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •