Revision: 37423
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at December 10, 2010 00:08 by BrunoDeBarros
Initial Code
/**
* Print an array (recursive) as PHP code (can be pasted into a php file and it will work).
* @param array $array
* @param boolean $return (whether to return or print the output)
* @return string|boolean (string if $return is true, true otherwise)
*/
function printArrayAsPhpCode($array, $return = false) {
if (count($array) == 0) {
if (!$return) {
print "array()";
return true;
} else {
return "array()";
}
}
$string = "array(";
if (array_values($array) === $array) {
$no_keys = true;
foreach ($array as $value) {
if (is_int($value)) {
$string .= "$value, ";
} elseif (is_array($value)) {
$string .= printArrayInPHPFormat($value, true) . ",\n";
} elseif (is_string($value)) {
$string .= "$value', ";
} else {
trigger_error("Unsupported type of \$value, in index $key.");
}
}
} else {
$string .="\n";
foreach ($array as $key => $value) {
$no_keys = false;
if (is_int($value)) {
$string .= "\"$key\" => $value,\n";
} elseif (is_array($value)) {
$string .= "\"$key\" => " . printArrayInPHPFormat($value, true) . ",\n";
} elseif (is_string($value)) {
$string .= "\"$key\" => '$value',\n";
} else {
trigger_error("Unsupported type of \$value, in index $key.");
}
}
}
$string = substr($string, 0, strlen($string) - 2); # Remove last comma.
if (!$no_keys) {
$string .= "\n";
}
$string .= ")";
if (!$return) {
print $string;
return true;
} else {
return $string;
}
}
Initial URL
http://terraduo.com
Initial Description
Prints an array (recursive) as PHP code (can be pasted into a php file and it will work). Note: This function can process arrays with integers/strings/sub-arrays. It is impossible to process resources (they have a state), and while it is possible to process objects, I didn't see a need for it. However, if you need it to support objects as well, I'll be more than happy to alter the function. Just drop a comment to let me know.
Initial Title
Output/Print an array as PHP code.
Initial Tags
php, array
Initial Language
PHP