don't worry too much about what my script does, just look at how it's constructed. In this case it's not inside a function but the array gets built into the html and then utilised.
See it working at http://property.digitalrice.com/muck/example.html - it's the iframe which uses the code, view source to see what's output.
<script language="Javascript">
var frm = parent.document.MyForm;
var updates = new Array();
var updatecnt = 0;
<?php
$animals = array('cow','dog','cat','lion','mouse');
$noises = array('moo', 'woof', 'miaow', 'roar', 'squeek');
$babies = array('calf', 'puppy', 'kitten', 'cub', '?');
for ($i = 0; $i < 5; $i++)
{
if ($animal == $animals[$i])
{
echo "updates[updatecnt++] = new Array('noiseMade','" . $noises[$i] . "');\n";
echo "updates[updatecnt++] = new Array('babyName','" . $babies[$i] . "');\n";
}
}
?>
if (updatecnt > 0)
for (var i = 0; i < updatecnt; i++)
frm[updates[i][0]].value = updates[i][1];
</script>