Re: Using Arrays in PHP convert a php array into a javascript array $a=array('one','two','three','four');
$vResult = arrayToJS4($a,"ArrayVal");
echo $vResult; //make javascript ready
function output($string)
{
$string = str_replace( array( '\\' , '\'' ), array('\\\\', '\\\'') , $string); //-> for javascript array
$string = str_replace( array("\r\n", "\r", "\n") , '<br>' , $string); //nl2br
return $string;
}
function arrayToJS4($array, $baseName ) {
//Write out the initial array definition
$output = $baseName . " = new Array(); \r\n ";
//Reset the array loop pointer
reset ($array);
//Use list() and each() to loop over each key/value
//pair of the array
while (list($key, $value) = each($array)) {
if (is_numeric($key)) {
//A numeric key, so output as usual
$outKey = "[" . $key . "]";
} else {
//A string key, so output as a string
$outKey = "['" . $key . "']";
}
if (is_array($value)) {
//The value is another array, so simply call
//another instance of this function to handle it
$output .= arrayToJS4($value, $baseName . $outKey);
} else {
//Output the key declaration
$output .= $baseName . $outKey . " = ";
//Now output the value
if (is_string($value)) {
//Output as a string, as we did before
$output .= "'" . output($value) . "'; \r\n ";
} else if ($value === false) {
//Explicitly output false
$output .= "false; \r\n";
} else if ($value === NULL) {
//Explicitly output null
$output .= "null; \r\n";
} else if ($value === true) {
//Explicitly output true
$output .= "true; \r\n";
} else {
//Output the value directly otherwise
$output .= $value . "; \r\n";
}
}
}
return $output;
} OutPut:
ArrayVal = new Array();
ArrayVal[0] = 'one';
ArrayVal[1] = 'two';
ArrayVal[2] = 'three';
ArrayVal[3] = 'four';
__________________ Thanks & Regards
Sabari... |