Converts a PHP Array into a JavaScript Array
12
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;
}






<?php
function myFunc($myVal1, $myVal2, &$myValRef = '') {
echo "Hello world!";
}
myFunc('1', '2'); // Generates a PHP Parse Error in 4.3.2
?>
What version of PHP was this built for/intended to be used in?
To fix this, use the static keyword in PHP:
function get_javascript_array($phpArray, $jsArrayName) {
/* This produces the same result as the "&$html = ''"
* in the function declaration was intended to, without
* a parse error.
*/
static $html = '';
$html .= $jsArrayName . " = new Array(); \r\n ";
foreach ($phpArray as $key => $value) {
$outKey = (is_int($key)) ? '[' . $key . ']' : "['" . $key . "']";
if (is_array($value)) {
/* Since $html is now a static variable, we no longer
* need to pass it into the recursive calls.
*/
get_javascript_array($value, $jsArrayName . $outKey);
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;
}
$javascript = json_encode($some_array);
There's also JSON-PHP available from PEAR if you need a pure-PHP implementation. Go here for more info on JSON.