Convert PHP array into HTML tag attributes separated by spaces



PHP Snippet 1:

$array=array(
    'attr1'=>'value1',
    'id'=>'example',
    'name'=>'john',
    'class'=>'normal'
);
$data = str_replace("=", '="', http_build_query($array, null, '" ', PHP_QUERY_RFC3986)).'"';
echo $data;

PHP Snippet 2:

$array = array(
  'attr1'=>'value1',
  'id'=>'example',
  'name'=>'john',
  'class'=>'normal');

foreach ($array as $key => $value) {
  echo $key . '="' . htmlspecialchars($value) . '" ';
}

PHP Snippet 3:

$array = array(
  'attr1'=>'value1',
  'id'=>'example',
  'name'=>'john',
  'class'=>'normal');

echo buildTag($array);

function buildTag ($array) {
  $tag = '';
  foreach ($array as $key => $value) {
    $tag .= $key . '="' . htmlspecialchars($value) . '" ';
  }
  return $tag;
}

PHP Snippet 4:

function buildAttributes($attributes)
{
    if (empty($attributes))
        return '';
    if (!is_array($attributes))
        return $attributes;

    $attributePairs = [];
    foreach ($attributes as $key => $val)
    {
        if (is_int($key))
            $attributePairs[] = $val;
        else
        {
            $val = htmlspecialchars($val, ENT_QUOTES);
            $attributePairs[] = "{$key}=\"{$val}\"";
        }
    }

    return join(' ', $attributePairs);
}

PHP Snippet 5:

[
    'name' => 'firstname',
    'value' => 'My Name',
    'required'
]

PHP Snippet 6:

name="firstname" value="My Name" required

PHP Snippet 7:

$array = array(
    'attr1' => 'value1',
    'id'    => 'example',
    'name'  => 'john',
    'class' => 'normal',
    'c'     => null,
    'd'     => '',
    'e'     => '"abc"'
);

$attributes = implode( ' ', array_filter( array_map( function ( $key, $value ) {
    return $value ? $key . '="' . htmlspecialchars( $value ) . '"' : false;
}, array_keys( $array ), $array ) ) );


echo "<div " . $attributes . "></div>";

PHP Snippet 8:

<div attr1="value1" id="example" name="john" class="normal" e="&quot;abc&quot;"></div>

PHP Snippet 9:

public static function arrayToStringTags( $array )
{
    $tags = '';

    if(!(is_array($array) && !empty($array)))
    {
        return $tags;
    }

    foreach($array as $key => $value)
    {
        $tags .= $key. '="'. $value. '" ';
    }

    return $tags;
}