tags:

views:

293

answers:

4

Hello! I have few FOREACH loops in php;

$c1 = 1;
$c2 = 1;
$c3 = 1;

foreach ($someArray as $a){
    echo $a;
    if (sizeof($someArray != $c1){
     echo " / ";
    }
    $c1++;
}

foreach ($otherArray as $b){
    echo $b;
    if (sizeof($otherArray != $c2){
     echo ", ";
    }
    $c2++;
}

// etc.

This seems somehow stupid, of course =) Is there any way to avoid declaring variables with same values and to use them in many FOREACH loops? Thanks in advance for any help!

+6  A: 

It appears you are trying to do what the following code does much better:

$line = implode(' / ', $someArray);
echo $line;

$line = implode(', ', $otherArray);
echo $line;
code_burgar
A: 

Don't know if it's necessarily bad what you're doing. Reusing a counter variable is (perhaps quietly) asking for trouble.

What about moving the initial declarations closer to the use? Putting the declarations closer to the action is clearer. As in:

$c1 = 1;

foreach ($someArray as $a){
    echo $a;
    if (sizeof($someArray) != $c1 {
        echo " / ";
    }
    $c1++;
}

$c2 = 1;

foreach ($otherArray as $b){
    echo $b;
    if (sizeof($otherArray) != $c2 {
        echo ", ";
    }
    $c2++;
}

$c3 = 1;

// etc.
John at CashCommons
Someone explain the downvote please?
John at CashCommons
Thanks a lot for help but previous answer was perfect for my needs ;-)
errata
ps: I didn't downvote because of that, honestly!
errata
No problem bomb_on ... I agree the answer you chose is better. I just wanted to learn what was wrong with my answer.
John at CashCommons
A: 

Wow! Many thanks for ultra-fast reply =) It is very clean and it is exactly what I needed!

Please tell me just one more thing.. is there a way to clean up this loop in a similar way?

if ($someArray){
    foreach ($someArray as $a){
     echo "[".$a."] ";
    }
}

Thanks for help! Stackoverflow is brilliant!! ;-)

errata
A: 

In answer to your second question:

if ($someArray){
    echo '['.implode('] [',$someArray).']';
    }
Rowan
Just brilliant!! Many many many thanks! =)
errata