Skip to content

Instantly share code, notes, and snippets.

@yookoala
Last active August 24, 2018 10:28
Show Gist options
  • Save yookoala/9f647e87df42cc7a918ecb75db738c32 to your computer and use it in GitHub Desktop.
Save yookoala/9f647e87df42cc7a918ecb75db738c32 to your computer and use it in GitHub Desktop.
Build HTML tag attributes with a given array.
<?php
/**
* Build HTML tag attributes string with a given array.
*
* Usage Example:
* echo '<img ' . http_build_attributes([
* 'src' => 'some-image-url',
* 'class' => ['img-responsive', 'decorative'],
* ]);
*
* Result:
* <img src="some-image-url" class="img-responsive decorative" />
*
* @author Koala Yeung <https://github.com/yookoala>dd
* @link https://gist.github.com/yookoala/9f647e87df42cc7a918ecb75db738c32
* #design_ref: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_attributes/7.x
*
* @param array $attr
* An assoc array of attributes with key as attribute name
* and value as attribute value(s).
*
* The value can be either an array of string or a string.
* If an object is given, it will be cast as string.
*
* @return string
*/
function http_build_attributes(array $attr): string
{
return implode(' ', array_map(function ($key) use ($attr) {
$value = is_object($attr[$key]) ? (string) $attr[$key] : $attr[$key];
$value = is_array($value) ? implode(' ', array_map(function ($item) {
return (string) $item; // cast all second level array value to string.
}, $value)) : (string) $value;
return sprintf('%s="%s"', htmlspecialchars($key), htmlspecialchars($value));
}, array_keys($attr)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment