M
M
Mikha Pankratov2016-07-04 11:48:37
PHP
Mikha Pankratov, 2016-07-04 11:48:37

How to iterate over a simple array of days of the week?

Good afternoon,
straight to the question) it’s hard to call it a question, and yet it caused problems ...
And so there is an array of days [1,2,3,4,5,6,7];
I have an interval from 3-2 i.e. it turns out includes all days of the week
I need to iterate over the array c 3 to 2 value, tell me how to do it without ifs) and pasta code)

for($i=1; $i<=7;$++){

}

Naturally, you can be smart, but this is not our method, the case is not only 3-2) I
need to sort through this case like this 3-4-5-6-7-1-2

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cat Anton, 2016-07-04
@frmax

Absolutely without if it will not work probably:

$n = 3;
$m = 2;
for ($i = $n; ; $i = ($i < 7 ? $i + 1 : 1)){
    echo $i . ' ';
    if ($i == $m) break;
}

https://ideone.com/ACJIjQ
Here's another option:
$n = 3;
$m = 2;

$i = $n - 1;
do {
  $d = $i % 7 + 1;
  echo $d . ' ';
  $i++;
} while ($d != $m);

https://ideone.com/1NKS0Q
And more:
$array = [1, 2, 3, 4, 5, 6, 7];
$n = 3;
$m = 2;

$i = array_search($n, $array);
$result = array_merge(array_slice($array, $i), array_slice($array, 0, $i));

https://ideone.com/g4ewhT

S
safenoob, 2016-07-04
@safenoob

3 to 2 is in reverse order, right? Then:

$reversed = array_reverse($array);
for($i=4; $i<6; $i++){
 echo $reversed[$i];
}

<= you can not put it in you loop in an infinite loop

M
Maxim Alekhin, 2016-07-04
@Settler1

I don't quite understand what you want, but if

need to loop through the array c 3 to 2 value

then just in reverse
for($i=3; $i>=2;$i--){
     echo "{$i}-";
}

or if
need to iterate over this case like this 3-4-5-6-7-1-2

then
foreach (array(3,4,5,6,7,1,2) as $i) {
     echo "{$i}-";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question