hamishtaplin hamishtaplin - 1 year ago 64
PHP Question

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 />


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.

Answer Source

I think this should do it:

$result = '<input '.join(' ', array_map(function($key) use ($attributes)
      return $attributes[$key]?$key:'';
   return $key.'="'.$attributes[$key].'"';
}, array_keys($attributes))).' />';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download