Using at least 4.3.2 of PHP, there is a problem with the pass-by-reference being given a default value in the function declaration. To be more precise, the following will demonstrate:
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 = '';
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; }
<?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.