insert php element into java script array

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

Post Reply
priyanka01
Forum Newbie
Posts: 1
Joined: Sun Nov 07, 2010 11:58 pm

insert php element into java script array

Post by priyanka01 »

Hi,

Code: Select all

      path=new Array();
      path[0]="<?= $field[0] ?>";
       path[1]="<?= $field[1] ?>";
i want to insert it in loop for example

Code: Select all

     path=new Array();
for (var i=0;i<path.length;i++){
  path[i]="<?= $field[i] ?>"; // but its not working

}
but the above code is not working please tell me another way
Last edited by Weirdan on Mon Nov 08, 2010 2:52 am, edited 1 time in total.
Reason: added syntax highlighting
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: insert php element into java script array

Post by Christopher »

You cannot do the second one because $field will only equal one value when you generate the Javascript. Either use the first method, or try generating JSON.
(#10850)
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: insert php element into java script array

Post by Jonah Bron »

Or this (untested)

Code: Select all

var path = ["<?php echo implode('", "', $field); ?>"];
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: insert php element into java script array

Post by Weirdan »

Jonah Bron wrote:Or this (untested)

Code: Select all

var path = ["<?php echo implode('", "', $field); ?>"];
json_encode is almost always better:

Code: Select all

var path = <?php echo json_encode($field);?>;
Post Reply