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

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))).' />';

$attr = array(
    'type'     => 'text',
    'id'       => 'contact-name',
    'name'     => 'contact-name',
    'required' => true,
    'value'    => '" <b>html</b> \'test\''
);

echo '<input '. implode(' ', array_map(
    function ($k, $v) { return $k .'="'. htmlspecialchars($v) .'"'; },
    array_keys($attr), $attr
)) .' />';

Tags:

Php

Arrays