PHP foreach: splitting a loop into two parts

I want to split the loop into two, but I can't figure it out!

I want to first create three elements from an array, and then display the remaining elements like this,

01 Home
02 Portfolio
03 Blog

{my website logo}

04 About
05 Contact
06 Feed

This is the code I'm stuck in

<?php
    $index = 0;

    foreach($items as $item) 
    {

    ?>
    <li>0<?php echo $index+1;?><a href="#"><?php echo $item['name'];?></a></li>
    <?php   
    $index ++;
    }

?>

Any ideas?

Thank.

+3
source share
4 answers
foreach ($items as $index => $item){
    echo /*<li>*/;
    if ($index == 2){
        echo /*logo*/;
    }
}

Do you need something like this?

+1
source

Perhaps array_slice is what you are looking for?

foreach (array_slice($items, 0, 3) as $item) {
    // print item
}

// display logo

foreach (array_slice($items, 2, 3) as $item) {
    // print item
}
+4
source

Try removing the loop together and using array_slice with implode ()

$first_three = array_slice($items, 0, 3); 

print implode("\n", $first_three);
print "LOGO";
print implode("\n", $items);
0
source

Maybe you can just create 2 for loops

<?php
for ($i=0; $i<3; $i++) {
?>
  <li>0<?php echo $i+1;?><a href="#"><?php echo $items[$i]['name'];?></a></li>
<?php 
}
?>

// display logo

<?php
for ($i=3; $i<count($items); $i++) {
?>
  <li>0<?php echo $i+1;?><a href="#"><?php echo $items[$i]['name'];?></a></li>
<?php 
}
?>
0
source

All Articles