Last active
June 18, 2019 19:05
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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