0

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.

5
  • How many times do you need it to loop through that array? Commented May 19, 2017 at 19:48
  • Google if statements. Commented May 19, 2017 at 19:48
  • @FunkDoc only 5 times Commented May 19, 2017 at 19:51
  • @FunkDoc and then start over Commented May 19, 2017 at 19:53
  • wordwrap(join($a),4,'<br>',1) #UnnecessaryCodeGolf Commented May 19, 2017 at 20:05

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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;
}
}
}

2 Comments

hey it works perfect but it repeats the process 9 times and the 9th result is only 3 numbers long :P
@Kevin.a Then you need to state more clearly what the exact expected output is. "Only 5 times" and "and then start over", as you commented earlier, is confusing. Please, properly formulate your exact problem and exact expected outcome.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.