简体   繁体   中英

PHP loop through array with condition

I have a loop which i made like this:

$arr = array(1, 2, 3, 4, 5, 6, 7);
foreach ($arr as &$value) {
    echo $value;
}

My loop result shows this:

1234567

I would like this to only show the numbers 1 to 4. And when it reaches 4 it should add a break and continue with 5671.

So an example is:

1234<br>
5671<br>
2345<br>
6712<br>

I have to make this but I have no idea where to start, all hints/tips are very welcome or comment any direction I should Google.

This produces the exact results you want

$arr = array(1, 2, 3, 4, 5, 6, 7);
$k=0;
for($i=1;$i<=5;++$i){
  foreach ($arr as &$value) {
    ++$k;
     echo $value;
     if($k %4 == 0) {
    echo '<br />';
   $k=0;
}
}
}

Here is more universal function- you can pass an array as argument, and amount of elements you want to display.

<?php

$array = array(1,2,3,4,5,6,7);

function getFirstValues(&$array, $amount){
    for($i=0; $i<$amount; $i++){
        echo $array[0];
        array_push($array, array_shift($array));
    }
    echo "<br />";
}

getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);


?>

The result is:
1234
5671
2345
6712

You are looking for array_chunk()

$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
$chunks = array_chunk($arr, 4);
foreach ($chunks as $array) {
    foreach ($array as $value) {
        echo $value;
    }
    echo "<br />";
}

The output is:

1234
5678
9101112
13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM