I am trying to familarise myself with for loop as I only understand the basics. I am trying to simplify the code below
$round1 = $max / 2;
$round2 = $round1 + ($max / 2 / 2);
$round3 = $round2 + ($max / 2 / 2 / 2);
$round4 = $round3 + ($max / 2 / 2 / 2 / 2);
$round5 ...
With this:-
$round = array($max/2);
for ($i=1;$i<$max;$i++) {
$round[] = $round[$i -1] + $max/pow(2, $i + 1);
}
And now for the next code:-
if($matchno <= $round[0]) {
$scores_round1.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[0] AND $matchno <= $round[1]) {
$scores_round2.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[1] AND $matchno <= $round[2]) {
$scores_round3.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[2] AND $matchno <= $round[3]) {
$scores_round4.= '['.$score1.', '.$score2.'],';
}
Can the above be used in a for loop to avoid using if() ?
Thanks for help
You can check for round1 and for the rest:
for ($i=1;$i<$max;$i++) {
if($matchno>$round[$i] AND $matchno <= $round[$i+1])
${'scores_round'.$i}.='['.$score1.', '.$score2.'],';
}
for($i=0;$i< count($round); $i++){
if($match < $round[$i]){
${"scores_round".$i}.= '['.$score1.', '.$score2.'],';
break;
}
}
By watching the if statements, we notice some things: First of all, there is no *else if* statement. That means that all if statement checks must be executed. Additionally, there is a check whether the $matchno is less than $round[0], without any check for greater than in this if statement (the first one). Another point is that $scores_roundX starts with X=1 and not 0. Obviously, you will have to use one if inside the loop. So, we are going to form loop code making some small tricks:
for($i = -1; $i < count($round)-1 ; ++$i){
if(($i = -1 OR $matchno > $round[$i]) AND ($matchno <= $round[$i+1])){
${"scores_round".$i+2} .= '['.$score1.', '.$score2.'],';
}
}