Bulding an HTML Attribute String From an Array

Problem

You have an associative array of attributes for an HTML element and want to convert it to a string.

Solution

Use the HTML::attributes() method.

echo HTML::attributes(array('id' => '123', 'class' => 'myclass'));

The above will build a string where the keys of the array are the attribute names and the values of the array are the attribute values. The output will be.

id="123" class="myclass"

Discussion

This is useful in HTML or Form macros.

It's useful whenever you need to build tag attributes in HTML or even XML.

See Creating Form Macros and Creating HTML Macros.

comments powered by Disqus