Reputation: 27
How to set the <select>
tag attributes from an associative array dynamically?
I need to send custom attributes from array and check if name is passed as key from array.
For Example Array:
$custom_attr = array("id"=>"year1","name"=>"year","class"=>"dp year form-control")
Creating <select>
tag like:
<select id="year1" name="year" class="dp year form-control">
.
.
.
</select>
Any idea about how to implement it? Thank you.
Upvotes: 0
Views: 277
Reputation: 2722
As far as I know, there is no easy way. Here is a more elegant approach:
function getTag($tag, $attributes) {
array_walk($attributes, function(&$val, $key) { $val = "$key='".htmlentities($val)."'"; });
$attributes = implode(' ', $attributes);
return "<$tag $attributes>";
}
echo getTag('select', array("id"=>"year1", "name"=>"year", "class"=>"dp year form-control"));
Upvotes: 0
Reputation: 719
A simple solution would be:
$result="<select ";
foreach($custom_attr as $key => $value){
$result.=$key.' = "'.$value.'" ';
}
$result.=">";
Upvotes: 1