Reputation: 4296
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.
Upvotes: 0
Views: 744
Reputation: 75
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
Upvotes: 2
Reputation: 1643
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;
}
}
}
Upvotes: 2
Reputation: 1135
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
Upvotes: 0