Quick Search:
 
 PHP Code: PHP to JavaScript Array Jump to:  
Category: >> PHP Code >> PHP to JavaScript Array  

<< lastnext >>

Snippet Name: 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.

Comment: (none)

Language: PHP
Highlight Mode: PHP
Last Modified: February 28th, 2009

<?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;
}
 
?>


 
   Home |    Search |    Code Library |    Sponsors |    Privacy |    Terms of Use |    Contact Us © 2003 - 2024 psoug.org