Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Dennis Castillo
Dennis Castillo
16,018 Points

More than 3 variables on the single loop.

Hello Guys,

Need some help about doing 3 variables on the single loop doing "for". I found this code and it is very useful for dual variable.

for ($i=1, $k=0; $i<=5; $i++, $k++) {
     echo "Num A: " . $i . "Num B: " . $k . "\n";
}
OUTPUT:
Num A: 1 Num B: 0
Num A: 2 Num B: 1
Num A: 3 Num B: 2
Num A: 4 Num B: 3
Num A: 5 Num B: 4  

But how about 3 variable or more. I tried add another variable inside of parenthesis but I'm having an error

    for ($w=1, $i=1, $k=0; $i<=5; $w<=5; $i++, $k++, $w++)

and I tried also to separate it: just an example

  for ($i=1, $k=0; $i<=5; $i++, $k++) {
       for ($w=1, $k=0; $i<=5; $i++, $k++) {

       }
}

but won't work and I think, what I'm doing is not the best practices... Am I?

My main goal is, the OUTPUT will be look like this:

Num A: 1 
    Num C: 1 Num B: 0
    Num C: 2 Num B: 1
    Num C: 3 Num B: 2
Num A: 2
    Num C: 1 Num B: 3
    Num C: 2 Num B: 4
    Num C: 3 Num B: 5    
Num A: 3
    Num C: 1 Num B: 3
    Num C: 2 Num B: 4
    Num C: 3 Num B: 5   
Num A: 4
    Num C: 1 Num B: 6
    Num C: 2 Num B: 7
    Num C: 3 Num B: 8
Num A: 5
    Num C: 1 Num B: 9
    Num C: 2 Num B: 10
    Num C: 3 Num B: 11   

Can you give me an advice what should I do to solve this problem?

Thanks and God Bless...

1 Answer

Eirik Anfinsen
Eirik Anfinsen
465 Points

Hi there,

I am not entirely sure if I understand what you are actually trying to do here, but I do think you might be complicating things a bit too much. Could this, slightly simpler, way of doing it work?

$c = 0;

for ($a=1; $a<=5; $a++) {
    echo "Num A" . $a . "\n";

    for($b=1; $b<=3; $b++) {
        echo "Num B: " . $b . " \t Num C: " . $c . " \n";
        $c++;
    }
}

This way, Num C will continuously increase by one while Num B will be reset to 1 for every time Num A is looped over. Does this make sense?

Dennis Castillo
Dennis Castillo
16,018 Points

Oh yeah, it make sense, I think I'm thinking too much. Thank you for clearing it for me (2 thumbs Up)