Using array to place multiple classes in a DIV

Asked

Viewed 43 times

0

I want to put several classes in one div, using Array, how could I do it? I tried using the code below, but it didn’t work.

<?php 
    $minhas_classes = array(
        'main-content' => 'main-content', 
        'post-count' => 'post-count', 
        'loop-style' => 'loop-style',
        'has-image' => 'has-image',
    );
?>

<div class="<?php echo $minhas_classes; ?>">
</div>
  • The last ,(comma) to your array is not necessary, other than that, I didn’t fully understand what you need. I could give some example?

  • But to print a content of array would be so: echo $minhas_classes["post-count"];, this way the second content would be printed.

  • Can’t you print them all at once? Without having to repeat this: $my_classes["post-count"], $my_classes["main-content"]

  • What’s the idea of having an associative array where the key is equal to the value?

  • @Anderson Carlos Woss I get it.

1 answer

3


I didn’t particularly understand why you defined a array associative, the keys being equal to the values. In my view, a array sequential would be enough and would be even simpler.

$classes = ['main-content', 'post-count', 'loop-style', 'has-image'];

To display all at once, just convert your array for string with the function join

$classes = join(' ', $classes);

So just do:

echo "<div class=\"{$classes}\">";

See working on Ideone | Repl.it

The result will be, as expected:

<div class="main-content post-count loop-style has-image">
  • That’s what I was looking for. Problem solved. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.