user12394904
user12394904

Reputation:

If count equals number, append class

So I have the variable $count that will give me a count. What would be the best approach to append a class name to the <div class="column"> section?

Here is sort of what I'm looking for:

Here is the code:

<?php $count = count($sub_items) ?>
<div class="column">
    <h1 class="title is-6 is-mega-menu-title mb-2"><?= $sub_item->get_title(); ?></h1>
    <?php if ($sub_child_items = $sub_item->get_sub_items()): ?>
        <?php foreach ($sub_child_items as $sub_child_item): ?>
        <a class="navbar-item" href="<?= $sub_child_item->get_url(); ?>">
            <?= $sub_child_item->get_title(); ?>
        </a>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

All help would be appreciated!

Upvotes: 1

Views: 210

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

I'll do something like this using switch and please note the last case default:

<?php
  $count = count($sub_items);
  $className = "column ";
  switch($count) {
    case 2:
      $className .= "is-half";
      break;
    case 3:
      $className .= "is-one-third";
      break;
    case 1:
    default:
      $className = ($count >= 4) ? "column is-one-quarter" : "column";
  }
?>
<div class="<?php echo $className; ?>">
    <h1 class="title is-6 is-mega-menu-title mb-2"><?= $sub_item->get_title(); ?></h1>
    <?php if ($sub_child_items = $sub_item->get_sub_items()): ?>
        <?php foreach ($sub_child_items as $sub_child_item): ?>
        <a class="navbar-item" href="<?= $sub_child_item->get_url(); ?>">
            <?= $sub_child_item->get_title(); ?>
        </a>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

Also, I would suggest to use <?php echo $varName; ?> instead of using <?= $varName; ?> for compatibility purposes.

Upvotes: 2

Related Questions