Sam Ram San Sam Ram San - 5 months ago 8
PHP Question

Specify from what index to start looping in a foreach loop

The content if pulled from a while loop that I used to fetch a query. I need to sort the content from different starting point of the array, let's say results from indexes 5to 8 and ignore 0 to 4 or 9 to 12.

<?php
$i='0';
foreach($articulos as $articdos){
?>
<div class="cajon4centro">
<div class="">
<a href="efecto.php?libelula=noticias&artic=<?= $articdos['id']; ?>&gen=<?= $articdos['genero']; ?>&id=<?= $articdos['id'] ?>">
<div class="c4img">
<img src="img/chica/<?= $articdos['foto']; ?>" alt="" />
<div class="titC4">
<?= $articdos['titulo']; ?>
</div>
</div>
</a>
</div>
</div>
<?php
if ($i++ == 3) break;
} ?>


As it is right now it all starts from index 0 and I want it to start after the 6th index... Can this be done?

Answer

Here's how you could do this using a counter:

<?php
    $i = 0;
    foreach($articulos as $articdos){
        if ($i >= 5 && $i <= 8) {
?>
    //Your HTML code here
<?php
        } // end if block
        $++i;
    } // end foreach loop
?>

During the loops where the if statement is false, no HTML code will be executed or output, and unless you're looping through thousands of records, the time taken during those loops where nothing is done will be negligible.

Instead of testing for a number, you could also test the data inside $articdos if you were only looking for specific records with specific data in them.

Comments