function make_js_array($jsArr, $php_array)
// Create JS Array $jsArr = javascript array name, $php_array is array to convert
{
echo "<script type=\"text/javascript\">\r\n";
echo "jsArr = new Array();\r\n";
foreach($php_array as $key => $value)
{
echo "jsArr[{$key}] = \"{$value}\";\r\n";
}
echo "</script>\r\n";
}
This is really quite simple. The entire content of my test php script follows, including the corrected make_js_array().
The most important thing to understand is where your code is executing. PHP code executes in the web server, before your browser even gets the HTML/Javascript file to display. Javascript executes in the browser, and the browser doesn't even know that the php code exists.
Here's my php test script:
<html>
<head>
<?php
$php_array1 = array("a","b","c");
$php_array2 = array("x","y","z");
function make_js_array($jsArr, $php_array)
// Create JS Array $jsArr = javascript array name, $php_array is array to convert
{
echo "<script type=\"text/javascript\">\r\n";
echo "$jsArr = new Array();\r\n";
foreach($php_array as $key => $value)
{
echo $jsArr."[{$key}] = \"{$value}\";\r\n";
}
echo "</script>\r\n";
}
make_js_array("first",$php_array1);
make_js_array("second",$php_array2);
?>
</head>
<body bgcolor="#FFFFFF">
<button onClick="alert(first[0]+first[1]+first[2]);">
Show First jsArray
</button>
<button onClick="alert(second[0]+second[1]+second[2]);">
Show Second jsArray
</button>
</body>
</html>