make 1st iteration of loop different to others


I'm a little bit out of practice and struggling to figure out some fairly basic PHP to get the result I'm after. I have the following code:

						//My ACF Fields for reference
						//faqs - field group
						//faq_question - sub-field
						//faq_answer - sub-field
						// check if the repeater field has rows of data
						if( have_rows('faqs') ):
						<div class="accordion" id="accordion2">
						<?php $i=1; while ( have_rows('faqs') ) : the_row(); ?>
							<div class="accordion-group">
								<div class="accordion-heading">
									<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse<?php echo $i; ?>">
										<?php the_sub_field('faq_question'); ?>
								<div id="collapse<?php echo $i; ?>" class="accordion-body collapse">
									<div class="accordion-inner">
										<?php the_sub_field('faq_answer'); ?>
							</div><!-- ACCORDIAN GROUP END -->
						<?php $i++; endwhile; ?>
						<?php endif; ?>

I simply want the 1st accordion group to have a slightly different class to any that follow it. It's so that the 1st accordion item is open with the other's closed once the page loads. I've tried doing something along the lines of <?php if $i=1 ?> but keep managing to break it. Hopefully that makes some sense?


  • James
    • WPMU DEV Initiate

    Thanks for this. I need to add a class of "in" to the 1st instance of <div id="collapse<?php echo $i; ?>"> for bootstrap to keep the 1st accordion item open rather than style it by creating inline css through jQuery. That may indeed be the best way, but I'd still be keen to find out how to do this htrough php by somehow checking the value of $i something along the lines of...

    <?php if($i=1) ?>
    <div id="collapse<?php echo $i; ?>" class="accordion-body collapse in">
    <?php else; ?>
    <div id="collapse<?php echo $i; ?>" class="accordion-body collapse">
    <?php $i++; endif; ?>

    I did try something like this but it was duplicating the results and I wasn't sure where I was going wrong.

  • Jude
    • DEV MAN

    Hey James

    Your love for PHP inspires me .. you can try this

    $first = true ;
    // The Loop
    while ( have_rows('faqs') ) : the_row();
    <div id="collapse" class="accordion-body collapse <?php if($first): echo 'in' ; $first = false; endif; ?>">
    <?php endwhile; ?>

    Does that help ?


Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.