Forum Moderators: coopster

Message Too Old, No Replies

while loop problem

         

skoff

6:33 pm on Sep 17, 2011 (gmt 0)

10+ Year Member



Hi everyone! Here's my problem!
What i want to do is for each goal that is scored i want to generate a number of passes between 0 and 2. What i have right now is working i just dont know how to integrate the passes. I want the passes to appear right after the goal number just like this :

Goal #1 (passes #1, passes #2), Goal #2 (passes #1), Goal #3 etc..

and if passes = 0 i dont want to see the parentheses..


$i=1;
$goals=5;
$passes = rand(0, 2);

while ($i<=$goals)
{
echo "Goal #" . $i . ",";
$i++;
}


Thanks to all of you i hope im clear :)

Readie

8:53 pm on Sep 17, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So, you want the following list (or something like it)?:

#1 (1),
#2 (2),
#3 (1),
#4 (2)

If so:

<?php

# Customization variables
$goals = 5;
$passes = range(0, 2);

//----

$max_pass = (count($passes) - 1);
if($max_pass >= 0) {
for($i = 1; $i < $goals; $i++) {
if($i > 0) {echo ",\n";}
echo 'Goal #' . $i . ': ' . $passes[rand(0, $max_pass)];
}
}

?>

penders

12:01 am on Sep 18, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I was going to post this earlier, but noticed that Readie had posted already, but anyway this is a bit different...

I would use for() loops, rather than while(), since you know the number of iterations before commencing the loop and is less prone to error. And I assume that $passes should be inside the goals loop and random for each goal?

$goals = 5; 
$maxPasses = 2;
$strGoals = '';
for ($g=1; $g<=$goals; $g++) {
$passes = rand(0, $maxPasses);
$strGoals .= ', Goal #'.$g;
if ($passes > 0) {
$strPasses = '';
for ($p=1; $p<=$passes; $p++) {
$strPasses .= ', passes #'.$p;
}
$strGoals .= ' ('.substr($strPasses,2).')';
}
}
echo substr($strGoals,2);

skoff

4:22 pm on Sep 18, 2011 (gmt 0)

10+ Year Member



Thanks penders really helpful! ;)