Reputation: 3970
How to do a snake loop in PHP or How to reverse PHP array after each time it loops I'm not sure what this method or technique is called so I'm just going to call it a snake loop.
Basically what I'm trying to do is loop through an array and then reverse the order of that array the next time it loops around.
I have come up with what seems to be a somewhat simple method of doing so, but I just wasn't sure if this was the correct technique or if there was a better way of doing so.
<?php
$rounds = 4;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ;
for($round = 1; $round <= $rounds; $round++){
echo "<h1>Round $round</h1>";
if ($round % 2 == 0) {
krsort($teams);
}else{
asort($teams);
}
foreach($teams as $team){
echo "$team<br />";
}
}
?>
Output:
Round 1
Team 1
Team 2
Team 3
Team 4
Round 2
Team 4
Team 3
Team 2
Team 1
Round 3
Team 1
Team 2
Team 3
Team 4
Round 4
Team 4
Team 3
Team 2
Team 1
Basically you can see that the array sorts ascending
if the $round
is an odd number and descending
if it's an even number.
Upvotes: 0
Views: 540
Reputation: 11764
I think reversing arrays is expensive, I think better will be to calculate the inverted index:
array A (6 length) 0,1,2,3,4,5
array B (5 length) 0,1,2,3,4
(len-1)-i
//^ this should calculate the inverted index, examples:
//in the array A, if you are index 3: (6-1)-3 = 2, so 3 turns to 2
//in the array A, if you are index 1: (6-1)-1 = 4, so 1 turns to 4
//in the array B, if you are index 3: (5-1)-3 = 1, so 3 turns to 1
//in the array B, if you are index 1: (5-1)-1 = 3, so 1 turns to 3
I don't write PHP, but it should be something like this:
teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4');
len = teams.length;
myindex; //initializing the var
for(i=0; i<len; i++){
echo "<h1>Round "+ (i+1) +"</h1>";
myindex = i;
if(i%2 == 0) {
myindex = ((len-1) - i);
}
echo team[myindex];
}
Upvotes: 1
Reputation: 4521
Modifying your code to implement array_reverse:
<?php
$rounds = 4;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ;
for($round = 1; $round <= $rounds; $round++){
echo "<h1>Round $round</h1>";
if ($round % 2 == 0) {
$teams = array_reverse($teams);
}
foreach($teams as $team){
echo "$team<br />";
}
}
?>
Upvotes: 1
Reputation: 24655
Use php's array_reverse function.
<?php
$rounds = 4;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ;
for($round = 1; $round <= $rounds; $round++){
echo "<h1>Round $round</h1>";
echo implode("<br/>", $teams);
$teams = array_reverse($teams);
}
?>
Upvotes: 2
Reputation: 1927
array_reverse is the function that returns the reverse of an array.
If you are trying to have the php array object have reversed content on each cycle, then you would need to set the array variable each time; otherwise, you can simply return the output of array_reverse on each cycle.
Upvotes: 0