Page 1 of 1

PHP array to Javascript Array

Posted: Mon Dec 22, 2003 10:16 am
by umcookeg
Hi all,

I have a php array and I need to get that array into javascript. Here is what I have tried so far.
<script>
var jsArray = new Array();
<?php
include_once 'testU.php';
$phparray = getNewsArray(); //funct. that builds array.
$numElements = count($phparray);
for( $i = 0; $i < $numElements; $i++)
{
echo("jsArray['$i'] = \"".$phparray[$i]."\";");
}
?>
Here is where I would probably write anouther loop
this time in javascript to iterate through my
jsArray. To get at the variables I need to work with.
</script>
I am VERY new to Javascript, I have tested the function in php that builds the array and it works fine. So I know that...
$phparray = getNewsArray();
this works.
If anyone can help me I would appreciate it. I have been trying for two days and I need to move on! :)

The php array is an array of strings, its simple only has a few elements.

Thanks in advance.

Posted: Mon Dec 22, 2003 2:46 pm
by Gen-ik
This should do the trick...

Code: Select all

<?php

$phpArr = array("apple","banana","cherry","doughnut");

// Create JS Array
echo "<script type="text/javascript">\r\n";
echo "jsArr = new Array();\r\n";

foreach($phpArr as $key => $value)
echo "jsArr[{$key}] = "{$value}";\r\n";

echo "</script>\r\n";

?>