problem with arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chelvan
    New Member
    • Aug 2008
    • 90

    problem with arrays

    hi
    forum



    i've an array, which read the data values from the database. now i need to pass this array into javascript. is it possible? how is it?

    thanks

    chel-1
  • ak1dnar
    Recognized Expert Top Contributor
    • Jan 2007
    • 1584

    #2
    I think you need to pass generated php array elements to a javascript array right? Have a look here, Its just an example to do the job. Hope this helps.
    Code:
    <?php
    $lang = array("PHP", "C++", "Python");
    var_dump($lang);
    ?>
    <html>
    <head>
    <script type="text/javascript">
    function myFunction(){
    var myArray = new Array();
    
    	<?php
    		foreach($lang as $key  => $value) {
    	?>
    		 myArray[<?php print $key?>] = "<?php print $value?>";
    
    	<?php
    	}
    	?>
    
    for (var i=0; i<myArray.length; i++) {
     alert(myArray[i]);
    }
    }
    </script>
    
    </head>
    
    <body onLoad="myFunction()">
    </body>
    </html>

    Comment

    • chelvan
      New Member
      • Aug 2008
      • 90

      #3
      Originally posted by ak1dnar
      I think you need to pass generated php array elements to a javascript array right? Have a look here, Its just a example to do the job. Hope this helps.
      Code:
      <?php
      $lang = array("PHP", "C++", "Python");
      var_dump($lang);
      ?>
      <html>
      <head>
      <script type="text/javascript">
      function myFunction(){
      var myArray = new Array();
      
      	<?php
      		foreach($lang as $key  => $value) {
      	?>
      		 myArray[<?php print $key?>] = "<?php print $value?>";
      
      	<?php
      	}
      	?>
      
      for (var i=0; i<myArray.length; i++) {
       alert(myArray[i]);
      }
      }
      </script>
      
      </head>
      
      <body onLoad="myFunction()">
      </body>
      </html>
      thanks its ok.
      but if i create the array from reading the database what will happen. is the above code is ok or am i need to change?

      chel-1

      Comment

      • ak1dnar
        Recognized Expert Top Contributor
        • Jan 2007
        • 1584

        #4
        As I said Its an example to do the job. You have to do the changes as required. Good luck!

        Comment

        • chelvan
          New Member
          • Aug 2008
          • 90

          #5
          Originally posted by ak1dnar
          As I said Its an example to do the job. You have to do the changes as required. Good luck!

          thanks ak1dnar.
          i try and come back again.



          thanks
          chel-1

          Comment

          Working...