Php To Javascript Array

Description: Given a PHP array (even a deep nested array), this function returns a string representation of that array as JavaScript array. Useful when using PHP to output JavaScript.

<?PHP
 
/*
 * 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;
}
 
?>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.