Re: Copying PHP array into a Javascript array

From: Date: Tue, 10 Apr 2007 21:50:50 +0000
Subject: Re: Copying PHP array into a Javascript array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-252480@lists.php.net to get a copy of this message
At 4/10/2007 01:36 PM, Otto Wyss wrote:
I've an array of file names $files = getFiles ($d); but would like to use this array in a JavaScript array. How can I copy this $files into a JavaScript variable?
As I'm sure you know, you can't literally copy the values from PHP into the javascript variable because the two languages are not running concurrently; first PHP runs and finishes, then javascript runs. What you can do is use PHP to build javascript code in which the array values are hardcoded. Say you want the javascript code to look like this:
        aFileArray = new Array('file1.jpg', 'file2.jpg', 'file3.jpg');
Then PHP can write this for example into the HTML head:
        // join array with quotes & commas
        $html = implode("', '", $files);
        // output javascript statement to browser
        echo "aFileArray = new Array('$html');";
or:
        echo <<<_
<script type="text/javascript"> aFileArray = new Array('$html'); </script> _; Regards, Paul __________________________ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com

« previous php.general (#252480) next »