Skip to content

Instantly share code, notes, and snippets.

@garvin
Last active March 6, 2017 22:04
Show Gist options
  • Save garvin/66cb2f78a67d188d5f884dcf6730b1ce to your computer and use it in GitHub Desktop.
Save garvin/66cb2f78a67d188d5f884dcf6730b1ce to your computer and use it in GitHub Desktop.
Quick & dirty output-an[-associative?]-array as a <table> function
/**
* Given an array, return its contents as a <table>
*
* @param mixed $r
* @return string If $r is an array, returns HTML of a <table> representing its contents.
* If $r is a string, returns that string with HTML entities converted.
* If $r is not a string or array, returns var_export($r, true) with HTML entities converted.
*/
function output_array_as_table($r) {
// function for doing some entitifying of strings
// probably should be a callback
$utf8_entities = function($string, $double_encode = true) {
return htmlentities((string) $string, ENT_QUOTES, "UTF-8", $double_encode);
};
if (is_array($r)) {
$out = "
<table><tbody>";
if (empty($r)) {
$out .= "
<tr><td colspan='2'>[empty array]</td></tr>";
}
else {
foreach ($r as $key => $val) {
$out .= sprintf(
"<tr>
<th>%s</th>
<td>%s</td>
</tr>",
$utf8_entities($key),
output_array_as_table($val)
);
}
}
$out .= "
</tbody></table>";
return $out;
}
if (is_string($r)) {
return $utf8_entities($r);
}
// not a string or array
return $utf8_entities(var_export($r, true));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment