Search code examples
phparraysforeachslicechunks

How to access three elements at a time in a loop?


I am having an issue with slicing from an array within a loop. What I am trying to do is iterate through an array and for each day return 3 different sections from the array. So for example day one should return 0,1,2 day 2 should return 3,4,5 etc... I am using array_slice() and it works for the first iteration, but on subsequent iterations, it only returns an array with 1 item in it. Any help would be much appreciated!!

Here is what I currently have:

foreach ($days as $day) {
    $j = $j + 1;
    var_dump("j" . $j);
    $activities = array_slice($activities, $j, $number_of_activities);
    var_dump("day" . $day);
    var_dump($activities);
} 

This is what is returned from var_dump...

string(2) "j1"
string(4) "day1"
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}
string(2) "j2"
string(4) "day2"
array(1) {
  [0]=> int(3)
}

Solution

  • I think it's doing what it should. Your reassigning activities to the slice result. So on the second iteration the array has 3 elements, you're starting at index two, so your slice only has one element (the last). I think you have a logic error. You probably need a temporary variable to hold the slice instead of overwriting activities.