-1

I have an array with the days of the week as the key (Mon, Tue, etc.). When going through the loop, I want to start on a particular day, then continue through the entire loop so I get all of the days. Any thoughts on how I can do this?

Rob
  • 50
  • 1
  • 1
  • 10
  • 2
    if you need to reset the iteration, start to some offset, you need some manual looping.. [check out this answer](http://stackoverflow.com/a/13382232/1978142) this may shed some light – user1978142 Jun 04 '14 at 15:18
  • You might look into [ArrayIterator::seek](http://www.php.net/manual/en/arrayiterator.seek.php) – SaganRitual Jun 04 '14 at 15:20
  • use a for loop instead of a foreach and you can then specify the iterator as the starting point of the array – Dave Jun 04 '14 at 15:31

3 Answers3

1

Edit: missed that you need to search by key. The following should work:

$days = array('wed' => 2, 'thu' => 3, 'fri' => 4, 'sat' => 5, 'sun' => 6, 'mon' => 0, 'tue' => 1);

if ($off = array_search('mon', array_keys($days))) {
    $result = array_merge(array_slice($days, $off, null, true), array_slice($days, 0, $off, true));
    echo print_r($result, true);
}

/*
Array
(
    [mon] => 0
    [tue] => 1
    [wed] => 2
    [thu] => 3
    [fri] => 4
    [sat] => 5
    [sun] => 6
)
 */

Explanation: use array_keys to find the numeric index of the key in the target array. Then use array_merge and array_splice to cut the array into two parts, everything from the index to the end of the array and everything from the beginning to before the index.

Andrew Mackrodt
  • 1,806
  • 14
  • 10
1

Use a for loop:

//there are 7 days of the week, 0-6 in an array
$days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
$startIndex = 4; //the INDEX day we are starting at
$offset = 0;  

//loop through 7 times regardless
for($i=0; $i<7; $i++){
    $dayIndex = $startIndex+$offset;
    echo $days[$dayIndex];           //day we want
    if($dayIndex == 6){              //we want to start from the beginning 
        $offset = $startIndex * -1;  //multiply by -1 so $startIndex+$offset will eval to 0
    }else{
        $offset++;
    }
}
user2537383
  • 315
  • 8
  • 19
-1

If you simply want to iterate from particular index, try

$days = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
foreach (array_slice($days, 2) as $day)
    echo($day . "\n");

It will iterate from index 2 till last item. And it will work exactly the same with any keys.

mlask
  • 337
  • 1
  • 9