Skip to content

Instantly share code, notes, and snippets.

@dhilowitz
Last active June 18, 2019 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhilowitz/cb6af14d687492622121ecb2cc71a614 to your computer and use it in GitHub Desktop.
Save dhilowitz/cb6af14d687492622121ecb2cc71a614 to your computer and use it in GitHub Desktop.
# Format a PHP array so that it looks nice. Almost like a pretty printed JSON string, but one that can be used directly in PHP without conversion.
<?php
function print_array($array) {
echo format_array($array);
}
function format_array($array, $initialTabDepth = 0) {
if(!is_array($array)) {
return "";
}
$string = "[\n";
foreach ($array as $key => $value) {
// Tab it up
for ($i=0; $i < $initialTabDepth + 1; $i++) {
$string .= "\t";
}
$string .= "\"" . $key . "\" => ";
if(is_array($value)) {
$string .= print_array($value, $initialTabDepth + 1);
} else if (is_integer($value)) {
$string .= $value;
} else if (is_bool($value)) {
$string .= ($value ? "true" : "false");
} else {
$string .= "\"" . $value . "\"";
}
$string .= ",\n";
}
for ($i=0; $i < $initialTabDepth; $i++) {
$string .= "\t";
}
$string .= ']';
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment