Skip to content
Advertisement

How do I map an associative array to html element attributes?

I’m building a basic form building class to speed my workflow up a bit and I’d like to be able to take an array of attributes like so:

$attributes = array(
   "type"         => "text",
   "id"           => "contact-name",
   "name"         => "contact-name",
   "required"     => true
);

and map that to the attributes of a html element:

<input type="text" id="contact-name" name="contact-name" required />

EDIT:

What is the cleanest way of achieving the above? I’m sure I could cobble something together with a loop and some concatenation but I get the feeling printf or similar could do it in a more elegant manner.

Advertisement

Answer

I think this should do it:

$result = '<input '.join(' ', array_map(function($key) use ($attributes)
{
   if(is_bool($attributes[$key]))
   {
      return $attributes[$key]?$key:'';
   }
   return $key.'="'.$attributes[$key].'"';
}, array_keys($attributes))).' />';
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement