Converts a PHP Array into a JavaScript Array





12
Date Submitted Tue. Sep. 12th, 2006 1:34 AM
Revision 1 of 1
Beginner Headzoo
Tags Array | JavaScript | PHP
Comments 3 comments
Given a PHP array (even a deep nested array), returns a string representation of that array as JavaScript array. Useful when using PHP to output JavaScript.

        /**
         * Converts a PHP array to a JavaScript array
         *
         * Takes a PHP array, and returns a string formated as a JavaScript array
         * that exactly matches the PHP array.
         *
         * @param       array  $phpArray  The PHP array
         * @param       string $jsArrayName          The name for the JavaScript array
         * @return      string
         */

        function get_javascript_array($phpArray, $jsArrayName, &$html = '') {
                $html .= $jsArrayName . " = new Array(); \r\n ";
                foreach ($phpArray as $key => $value) {
                        $outKey = (is_int($key)) ? '[' . $key . ']' : "['" . $key . "']";

                        if (is_array($value)) {
                                get_javascript_array($value, $jsArrayName . $outKey, $html);
                                continue;
                        }
                        $html .= $jsArrayName . $outKey . " = ";
                        if (is_string($value)) {
                                $html .= "'" . $value . "'; \r\n ";
                        } else if ($value === false) {
                                $html .= "false; \r\n";
                        } else if ($value === NULL) {
                                $html .= "null; \r\n";
                        } else if ($value === true) {
                                $html .= "true; \r\n";
                        } else {
                                $html .= $value . "; \r\n";
                        }
                }
               
                return $html;
        }
 

Sean Hickey

www.headzoo.com
http://www.headzoo.com
http://www.480x.com
http://www.wpplugins.org

Comments

Comments PHP Incompatibility
Mon. Sep. 18th, 2006 7:27 AM    Helper dohpaz
Comments JSON
Fri. Oct. 20th, 2006 9:10 PM    Beginner stalfos
Comments Escape values
Fri. Sep. 22nd, 2006 6:10 PM    Newbie yennieb

Voting