I have a PHP foreach loop which outputs a series of items.
What I want to achieve is some code (a div) wrapped around items 1 & 2 and also wrapped around 3 & the very last item.
Here is the PHP:
<?php foreach ($this->item->extra_fields as $key=>$extraField): ?>
<div class="<?php echo ($key%2) ? "odd" : "even"; ?> type<?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
<span class="itemExtraFieldsValue"><?php echo JHTML::_('content.prepare', $extraField->value); ?></span>
<div class="clearfix"></div>
</div>
<?php $counter++; endforeach; ?>
Any ideas on how I could achieve this?
Many thanks in advance.
Maybe something like this, forgive me my PHP is a bit rusty.
<?php foreach ($this->item->extra_fields as $key=>$extraField): ?>
<?php
$len = count($this->item->extra_fields);
if ($key == 1 || $key == 2 || $key == 3 || $key == len) {
echo "<div>";
}
?>
<div class="<?php echo ($key%2) ? "odd" : "even"; ?> type<?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
<span class="itemExtraFieldsValue"><?php echo JHTML::_('content.prepare', $extraField->value); ?></span>
<div class="clearfix"></div>
</div>
<?php
if ($key == 1 || $key == 2 || $key == 3 || $key == len) {
echo "</div>" ;
}
?>
<?php $counter++; endforeach; ?>
Might have to account for the length of the list, so your last check might be len + 1
, and your first 3 checks might be (0, 1, and 2), it depends on what the $key value is.
It's a bit confusing what the $counter++
part of your code does in a foreach
, perhaps you should be using that for your modulus and in place of the key.
Regardless it's difficult to code up a solution as I believe your code snippet is incomplete, and it would also be helpful to know what the data is that we are looping through and the intended output of just having the first 3 and the last item wrapped in a div.