- php — How do I map an associative array to html element attributes?
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Share solution ↓
- Additional Information:
- Didn’t find the answer?
- Similar questions
- Write quick answer
- About the technologies asked in this question
- PHP
- HTML
- Welcome to programmierfrage.com
- Get answers to specific questions
- Help Others Solve Their Issues
- Convert PHP array into HTML tag attributes separated by spaces
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Answer
- Solution:
- Share solution ↓
- Additional Information:
- Didn’t find the answer?
- Similar questions
- Write quick answer
- About the technologies asked in this question
- PHP
- HTML
- Welcome to programmierfrage.com
- Get answers to specific questions
- Help Others Solve Their Issues
php — How do I map an associative array to html element attributes?
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:
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.
Answer
Solution:
I think this should do it:
$result = ' return $key.'="'.$attributes[$key].'"'; >, array_keys($attributes))).' />';
Answer
Solution:
$attr = array( 'type' => 'text', 'id' => 'contact-name', 'name' => 'contact-name', 'required' => true, 'value' => '" html \'test\'' ); echo ', array_keys($attr), $attr )) .' />';
Answer
Solution:
Something along these lines (a very simple method — of course you can extend this, but this will provide you with the basic functionality):
$output = " $value) < $output .= $key.'="'.$value.'" '; >$output .= "/>";
Answer
Solution:
As http_build_query is meant for stringify associative array’s, I hoped to stumble upon such a solution here. Didn’t find one, so here’s my ‘one-liner’:
- it converts boolean-values to 1/0 (instead of ommiting them if false, which can be achieved by using array_filter, but results in double function-calls);
- doesn’t handle array’s in a desired way;
- Needs urldecode after http_build_query to get back the encoded spaces (for example, when having multiple html-classes in an attribute).
So, only suitable in certain situations!
Answer
Solution:
$output = ' $value) < if (is_bool($value)) < if ($value) $output .= $name . ' '; >else < $output .= sprintf('%s="%s"', $name, $value); >> $output .= '>';
if ($value) $output .= $name . ' ';
if ($value) $output .= sprintf('%s="%s"', $name, $name);
Answer
Solution:
This is a solution I use in my projects:
function html_attributes($attributes)
Answer
Solution:
$input_attrs = array( 'type' => 'text', 'placeholder' => 'Placeholder', 'value' => 'the value' ); //Use & for modify current item in array array_walk($input_attrs, function (&$item, $key) < $item = $key . '="' . $item . '"'; >); $input = '';
Answer
Solution:
Old school PHP 4 — 5.2 version. This also allows for an array for the class attribute.
$attributes = array( "type" => "text", "class" => array("one", "two"), "id" => "contact-name", "name" => "contact-name", "required" => true ); printf( '', join(' ', array_map('mapAttr', array_keys($attr), array_values($attr))) ); function mapAttr($key, $value) < if (is_array($value)) < return mapAttr($key, join(' ', $value)); >if (is_bool($value)) < return $value ? $key : ''; >return sprintf('%s="%s"', $key, $value); >
Answer
Solution:
function html_attributes(array $array) < return implode(' ', array_map(function ($key, $value) < if (is_array($value)) < $value = implode(' ', $value); >return $key . '="' . htmlspecialchars($value) . '"'; >, array_keys($array), $array)); >
This one allow to use array of attribute’s value. Ex.
$attrs = [ 'class' => ['foo', 'bar'], 'id' => 'baz', ]; echo html_attributes($attrs); // -> `class="foo bar" `
Answer
Solution:
function createDomElement($tag, $attributes, $inner = '', $closingTag = true) < return ', array_keys($attributes)))) . '>' . $inner . ($closingTag ? '' . $tag . '>' : ''); >
Answer
Solution:
This would be my solution, hope it helps!
- Used === to check for the boolean and that it’s true in a single check
- Used addslashes to escape double-quotes on value being placed inside double-quotes
- Looped on the array itself and updated its own values in preparation for implode
- Imploded the values together with a space which means there is no need to trim any white space. Any values turned into » as a result of the boolean check would simply not show up.
foreach($attr as $k=>$v) < $attr[$k] = $v===true?$k:"$k=\"".addslashes($v)."\""; >echo "";
Answer
Solution:
Something I didn’t see yet, using php’s .
'slow', 'ball' => false, 'globe' => true, ]; $attributes = array_reduce( array_keys( $attributeCollection ) , fn( $carry , $name ) => vsprintf( '%s %s="%s"' , [ $carry , $name , $attributeCollection[ $name ] , ]) ) $markup = ' '; echo $markup;
vsprintf( '%s %s="%s"' , [ $carry , $name , $in[ $name ] , ] ) ); return $out; > $attributes = [ 'speed' => 'slow', 'ball' => false, 'globe' => true, ]; $markup = ' '; echo $markup;
is_bool($in[$name]) && true !== $in[$name] # fn( $carry , $name ) => !$in[$name] ? $carry : vsprintf( '%s %s="%s"' , [ $carry , $name , is_bool($in[$name]) ? $name : $in[ $name ] , ] ) ); return $out; > $attributes = [ 'speed' => 'slow', 'ball' => false, 'globe' => true, ]; $markup = ' '; echo $markup;
Share solution ↓
Additional Information:
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
HTML
HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
Convert PHP array into HTML tag attributes separated by spaces
Solution:
You can also use this easy one line code, please follwo below code::
$array=array( 'attr1'=>'value1', 'id'=>'example', 'name'=>'john', 'class'=>'normal' ); $data = str_replace("=", '="', http_build_query($array, null, '" ', PHP_QUERY_RFC3986)).'"'; echo $data;
Answer
Solution:
I use the following function:
function buildAttributes($attributes) < if (empty($attributes)) return ''; if (!is_array($attributes)) return $attributes; $attributePairs = []; foreach ($attributes as $key =>$val) < if (is_int($key)) $attributePairs[] = $val; else < $val = htmlspecialchars($val, ENT_QUOTES); $attributePairs[] = "=\"\""; > > return join(' ', $attributePairs); >
It correctly escapes special html characters and supports boolean attributes (attributes without value). The following input:
[ 'name' => 'firstname', 'value' => 'My Name', 'required' ]
name="firstname" value="My Name" required
Answer
Solution:
Use a foreach loop to get the value and key.
$array = array( 'attr1'=>'value1', 'id'=>'example', 'name'=>'john', 'class'=>'normal'); foreach ($array as $key => $value)
If you wanted to use a function, you could just make your own such as the following.
$array = array( 'attr1'=>'value1', 'id'=>'example', 'name'=>'john', 'class'=>'normal'); echo buildTag($array); function buildTag ($array) < $tag = ''; foreach ($array as $key =>$value) < $tag .= $key . '="' . htmlspecialchars($value) . '" '; >return $tag; >
Answer
Solution:
You could also utilize array_map() in conjunction with array_keys() to build your $key=$value string.
Wrapped in array_filter() to remove empty items and ultimately use implode() to glue your items together.
$array = array( 'attr1' => 'value1', 'id' => 'example', 'name' => 'john', 'class' => 'normal', 'c' => null, 'd' => '', 'e' => '"abc"' ); $attributes = implode( ' ', array_filter( array_map( function ( $key, $value ) < return $value ? $key . '="' . htmlspecialchars( $value ) . '"' : false; >, array_keys( $array ), $array ) ) ); echo " ";
Answer
Solution:
The shortest one-line function to do that would be:
function add_attributes($attributes)< return urldecode(http_build_query(array_map(function($v)< return '"'.((string) $v).'"'; >, $attributes), '', ' ')); >
$array=array( 'attr1'=>'value1', 'id'=>'example', 'name'=>'john', 'class'=>'normal' ); echo ' ';
Answer
Solution:
You can use this function:
public static function arrayToStringTags( $array ) < $tags = ''; if(!(is_array($array) && !empty($array))) < return $tags; >foreach($array as $key => $value) < $tags .= $key. '="'. $value. '" '; >return $tags; >
Share solution ↓
Additional Information:
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
HTML
HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.