Convert PHP array into HTML tag attributes separated by spaces

Viewed 5071

I need to convert a PHP array into HTML tag attributes, with spaces and quotes, this is an example:

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

This is the result I need to achieve:

attr1="value1" id="example" name="john" class="normal"

There is any PHP function to do it?

I am trying these:

  • http_build_query
  • array_walk
6 Answers

You could also utilize array_map() in conjunction with array_keys() to build your $key=$value string.

Wrapped in array_filter() to remove empty items and ultimately use implode() to glue your items together.

$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>";

Result:

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

The shortest one-line function to do that would be:

function add_attributes($attributes){
      return urldecode(http_build_query(array_map(function($v){ return '"'.((string) $v).'"'; }, $attributes), '', ' '));
}

You can use it like this:

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

echo '<div '.add_attributes($array).'></div>';

will produce:

<div attr1="value1" id="example" name="john" class="normal"></div>

You can use this function:

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

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

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

    return $tags;
}
Related