how to pass PHP array to javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • unpresedented
    New Member
    • Feb 2010
    • 11

    how to pass PHP array to javascript

    I have a php array that consists of 4 string elements :
    $arr = Array("A", "B", "C", "D");

    i want to pass this array as an argument to a javascript function and alert the contents, how ? so i need something like this in javascript:
    Code:
    function x(my_arr) {
    for(i=0;i<my_arr.length;i++)
      alert(my_arr[i]);
    }
    I do not want a solution like this : function ('<?=$arr?>') { ... }

    whenever I try to pass it, the alert function of javascript displays the word "ARRAY" ...
    thanx in advance ..
    Last edited by Dormilich; Feb 13 '10, 10:59 AM. Reason: Please use [code] tags when posting code
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    obviously. if you print out a PHP array, that’s what you get. you have to print it in such a way, that it defines the array in JavaScript.
    Code:
    $str = "[";
    foreach ($arr as $val)
    {
        $str += $val . ", ";
    }
    echo substr($str, 0, -1) . "];";

    Comment

    • unpresedented
      New Member
      • Feb 2010
      • 11

      #3
      thank you so much for this cool idea ..
      I appreciate it ...

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        that’s plain JavaScript printed by PHP, nothing special.

        Comment

        • xNephilimx
          Recognized Expert New Member
          • Jun 2007
          • 213

          #5
          you could also use json_encode function if you have php 5.2+

          Code:
          echo json_encode( $php_array );
          The output will be the same as dormilich method.
          Be aware that in javascript there are no associative arrays like in php (arrays with string keys instead of numbers), so json_encode will encode such array as an object.

          Comment

          Working...