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.
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.
You can use the PHP array_values() function to get all the values of 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.
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.
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))).' />';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With