phphtmlarraysattributesassociative-array

Convert an associative array into a string of HTML element attribute assignments


I want to convert array values into string. What should I use to join them as presented in goal?

Should I use serialize() or implode() or http_build_query() or array_walk() ?

$attributes = array(
    'autocomplete' => 'off',
    'class' => 'email',
    'id' => 'myform'
);

echo http_build_query($attributes, '', '" ');

// output
autocomplete=off" class=email" id=myform

Goal:

// output 
autocomplete="off" class="email" id="myform"

Edit:

I used array_walk() to gain goal

function myfunction($value, $key) {
    echo $key . '=" ' . $value . ' " ';
}

array_walk($atributes, "myfunction");

Solution

  • It looks like you want to combine these into a string for outputting on an HTML tag.

    This reusable function should produce your desired result:

    function get_attribute_string($attr_array) {
        $attributes_processed = array();
        foreach($attr_array as $key => $value) {
            $attributes_processed[] = $key . '="' . $value . '"';
        }
    
        return implode($attributes_processed, ' ');
    }
    
    $atributes = array(
        'autocomplete' => 'off',
        'class' => 'email',
        'id' => 'myform'
    );
    
    // this string will contain your goal output
    $attributes_string = get_attribute_string($atributes);
    

    P.S. atributes should have three Ts - attributes - mind this doesn't catch you out!