1

How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it.

 <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>
<li>
    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>
    </a>
    <?php if($param->count): ?>
    <div class="wpjb-widget-item-count">
        <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
    </div>
    <?php endif; ?>
</li>
<?php endforeach; ?>
Luke
  • 35
  • 5

5 Answers5

1

There are three methods:

Method 1: foreach with a counter var

$counter = 1;

foreach($locations as $location) {
    // use $location here

    if($counter++ == 5) {
        break;
    }

}

Method 2: foreach using $key=>$val

foreach($locations as $key=>$val) {

    // Your content goes here
    if($key === 4) {
        break;
    }
}

Method 3: for loop

for($i = 0; $i < 5; $i++) {
    // Use $locations[$i] here and do something with it
}
Xatenev
  • 6,383
  • 3
  • 18
  • 42
1

You can use array_slice() first to get a new array with no more than 5 elements.

$locations = array_slice($locations, 0, 5);

Then everything unchanged.

LF00
  • 27,015
  • 29
  • 156
  • 295
0

Using a counter variable into your loop you can control/limit to any number.

Example:

$counter = 0;
foreach($locations as $location):
    if($counter++ == 5): 
        break;
    // Your other content goes here
    endif;
endforeach;
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
0

Add a variable ... increment it each iteration ... after reach 5 just break loop.

<?php $i = 1;?>         

<?php if(!empty($locations)): foreach($locations as $location):  ?>
    <?php if(empty($location["title"])) continue; ?>
    <li>
        <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
            <?php esc_html_e($location["title"]) ?>
        </a>
        <?php if($param->count): ?>
        <div class="wpjb-widget-item-count">
            <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
        </div>
        <?php endif; ?>
    </li>
    <?php  if ($i++ == 5) break; ?>
    <?php endforeach; ?>
Minar Mnr
  • 1,376
  • 1
  • 16
  • 23
0

You can use for():

<?php if(!empty($locations)): 
for($i=0; $i<5; $i++) {
    $location = $locations[$i];
    <?php if(empty($locations["title"])) continue; ?>
        <li>
            <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
                <?php esc_html_e($location["title"]) ?>
            </a>
            <?php if($param->count): ?>
            <div class="wpjb-widget-item-count">
                <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
            </div>
            <?php endif; ?>
        </li>
}
Annapurna
  • 529
  • 1
  • 6
  • 19