tags:

views:

41

answers:

3

I want to make a conditional if statement that does this

if($get_['b']=="1") {

$offer1a=$offer1XXX;
$offer1e=$offer1YYY;

$offer2a=$offer2XXX;
$offer2e=$offer2YYY;

$offer3a=$offer3XXX;
$offer3e=$offer3YYY;

$offer4a=$offer4XXX;
$offer4e=$offer4YYY;

}

All the way to offer #12. It seems like a lot to write out. There are other values like $offer1b that I want left alone. What's the best way to do this. I think an array, but I'm unclear on how to get it done.

A: 

If you were to change $offer to an array, you could do something like this:

if ($get_['b'] == "1") {
    for ($i = 1; i <= 12; i++) {
        $offer[$i]['a'] = $offer[$i]['XXX'];
        $offer[$i]['e'] = $offer[$i]['YYY'];
    }
}
Ben Blank
+1  A: 

I'm sure there are a thousand more optimizations, but to do literally what you're asking, you could use a for loop as such:

if ($_GET['b'] == 1) {
  for ($k = 1; $k <= 12; $k++) {
    ${"offer${k}a"} = ${"offer${k}XXXX"};
    ${"offer${k}e"} = ${"offer${k}YYYY"};
  }
}

A better solution would be to use an array instead of all these individual variables:

for ($k = 1; $k <= 12; $k++) {
  $offers[$k]['a'] = $offers[$k]['XXXX'];
  $offers[$k]['e'] = $offers[$k]['YYYY'];
}
pix0r
Thanks to the other two of you who gave solutions, this one worked just fine. I am slowly losing my fear of arrays.
pg
A: 

Arrays are your friend:

for ($i = 1; $i <= 12; ++$i) {
    $offer[$i]['a'] = $offer[$i]['XXX'];
    $offer[$i]['e'] = $offer[$i]['YYY'];
}

Without seeing how the offer variables are initially populated, I can't help much further. Perhaps something like this:

$offer = array(
    1 => array(
       'a' => "something",
       'b' => "somethingElse",
        'XXX' => "blah",
        'YYY' => "foo"  
    ),
    array(
        'a' => '...'
    )
);
nickf