RE: PHP arrays and javascript

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



<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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux