0

Is there php function to convert Array to be like key=value in html, and if not what's the best practices ?

Input

$htmlOptions = array('class'=>'container');

...

<div <?php someFunction($htmlOptions); ?> ></div>

Output

<div class="container"></div>
2
  • Nothing out of the box. You'd have to use a foreach Commented Mar 18, 2014 at 9:59
  • 2
    For your specific example you should look at CHtml::tag() Commented Mar 18, 2014 at 10:00

3 Answers 3

4

This should be fine:

function printAttributes($array) {
    $attrArray = array();
    foreach ($array as $name => $value) {
        $attrArray[] = $name. '="' . $value . '"';
    }

    return join(' ', $attrArray);
}

// (...)

$htmlOptions = array('class'=>'container');

And then in HTML:

<div <?= printAttributes($htmlOptions); ?>></div>
Sign up to request clarification or add additional context in comments.

Comments

1

Well, you can iterate through the array like this

foreach($array as $key => $value){
   echo "This is the key : " . $key . "<br />This is the value : " . $value;
}

This way you'll get both, the array keys and the values.

Comments

1

Something simpler using a foreach

<?php
$htmlOptions = array('class'=>'container');
foreach($htmlOptions as $k=>$v)
{
    echo "<div $k='$v'></div>";
}

OUTPUT :

<div class='container'></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.