I was looking for a solution to this question and I know it's been 10 years old but halfway the page, I thought: why not string replace on a json encode. It will give you easy access on how to configure the string. Also, it's a oneliner that avoids a (foreach) loop.
It would look something like this:
$wrapperAttributesString = str_replace(['{"' , '"}', '":', '","'],['' , '', '=', ' '], json_encode($wrapperAttributes));
So, bassically what happens here is:
$wrapperAttributes['class'] = 'hi__stack--overflow';
$wrapperAttributes['style'] = 'overflow: stack; ';
$wrapperAttributes['id'] = 'oneliner_array_with_keys_tostring_attributes';
//if we were to json encode this array: it would result in this:
// {"class":"hi__stack--overflow","style":"overflow: stack; ","id":"oneliner_array_with_keys_tostring_attributes"}
now the str_replace first argument takes an array with find what, the second is an array to replace that with.
so it does:
find {" and replace with nothing;
find }" and replace with nothing;
find ": and replace with =;
find "," and replace with " ; to close the attribute and space to chain next
the output would be
class="hi__stack--overflow" style="overflow: stack; "
id="oneliner_array_with_keys_tostring_attributes"
Now if you woud like to have comma separated instead of space separated string, just change the last replace into find "," with ','
the output would become
class="hi__stack--overflow",style="overflow: stack;
",id="oneliner_array_with_keys_tostring_attributes
Be aware, that this might be safe for html attributes (considering the values should never have a doubleqoute), but I would definitly not use it where the values can have the same combinations as the replaces have.
This is my first post, so, if you have any feedback. Feel free to let me know, also, if I by accident, did not abide by any standards, then let me know and i wil change it asap :)