You can use PHP’s array_map
function or loop through the array to generate the attribute string, and then insert it into the HTML markup. Here’s an example code:
<?php
$section_attrs = array(
'id' => '',
'class' => 'section-content',
'aria-label' => 'Site content',
);
// Function to generate attributes
function render_attributes($attributes) {
$result = '';
foreach ($attributes as $key => $value) {
if (!empty($value)) { // Ignore empty values
$result .= sprintf('%s="%s" ', $key, htmlspecialchars($value, ENT_QUOTES));
}
}
return trim($result); // Remove trailing space
}
// Generate attributes string
$attrs_string = render_attributes($section_attrs);
// Output the markup
echo '<section ' . $attrs_string . '></section>';
?>
Output:
<section class="section-content" aria-label="Site content"></section>
Explanation:
- Empty value check: We make sure that the attribute value is not empty to avoid generating empty attributes like
id=""
. - Escaping values: We use
htmlspecialchars
to prevent potential XSS vulnerabilities. - String formatting:
sprintf
simplifies the assembly of thekey="value"
string.
If you need a more dynamic approach for other tags, this solution is easily adaptable.