RE: [PHP] PHP arrays and javascript

From: Date: Fri, 26 Nov 2004 20:06:25 +0000
Subject: RE: [PHP] PHP arrays and javascript
Groups: php.general 
Request: Send a blank email to php-general+get-202917@lists.php.net to get a copy of this message
<snip> i know this probally a simple question, but it has been stumping me for quite some time now. How do i pass a php array to a javascript? i tryed: <script language="javascript"> var myarray = new Array(<?PHP echo $myarray; ?>); </script> but it didn't work. Anybody got any ideas? </snip> You need to generate the javascript array from your PHP array. Example: In your script create a php array of the values you wish to use. Using indeces is not essential. If you do not use them, you can just use a counter var when you loop through the array to create the indeces for the JS array. <?php $arrayVar = array('first index'=>'item 1', 'second index'=>'item 2', 'third index'=>'item 3'); $jsVar = "var myArray = new Array();\n"; foreach ($arrayVar as $idx=>$val) { $jsVar .= "myArray['{$idx}'] = {$val}\n"; } ?> The final output of this will be: var myArray = new Array(); myArray['first index'] = 'item 1'; myArray['second index'] = 'item 2'; myArray['third index'] = 'item 3'; HTH, Pablo

« previous php.general (#202917) next »