Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map an associative array to html element attributes?

Tags:

I'm building a basic form building class to speed my workflow up a bit and I'd like to be able to take an array of attributes like so:

$attributes = array(    "type"         => "text",    "id"           => "contact-name",    "name"         => "contact-name",    "required"     => true ); 

and map that to the attributes of a html element:

<input type="text" id="contact-name" name="contact-name" required /> 

EDIT:

What is the cleanest way of achieving the above? I'm sure I could cobble something together with a loop and some concatenation but I get the feeling printf or similar could do it in a more elegant manner.

like image 201
hamishtaplin Avatar asked Aug 06 '13 13:08

hamishtaplin


People also ask

How do you access the elements of an associative array?

The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP. Although the array_keys() function can be used to get an indexed array of keys for an associative array.

How can we access a specific value in an associative array in PHP?

You can use the PHP array_values() function to get all the values of an associative array.

Is $_ POST an associative array?

The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.

How do you append an associative array in PHP?

Use the array_merge() Function to Add Elements at the Beginning of an Associative Array in PHP. To add elements at the beginning of an associative, we can use the array union of the array_merge() function.


1 Answers

I think this should do it:

$result = '<input '.join(' ', array_map(function($key) use ($attributes) {    if(is_bool($attributes[$key]))    {       return $attributes[$key]?$key:'';    }    return $key.'="'.$attributes[$key].'"'; }, array_keys($attributes))).' />'; 
like image 157
Alma Do Avatar answered Nov 27 '22 16:11

Alma Do