Forum Moderators: coopster

Message Too Old, No Replies

simplify an elseif

         

mrnoisy

11:11 pm on Jan 21, 2005 (gmt 0)

10+ Year Member



I know there will be a simple way to do this but I can't figure it out without an infinite elseif structure.

Basically for every four $totalamount purchased a $freebonus is to be added.


if ($totalamount >= 4 and $totalamount < 8)
{
$freebonus = 1;
}
elseif ($totalamount >= 8 and $totalamount < 12)
{
$freebonus = 2;
}
elseif ($totalamount >= 12 and $totalamount < 16)
{
$freebonus = 3;
}

lZakl

1:12 am on Jan 22, 2005 (gmt 0)

10+ Year Member



Would something like this do the trick..?

<?

// This is your input number... It wil be the one
// that changes via form input or whatever, for
// testing I just put 158 here to make sure the
// script works ok.
$totalamount = 158;

$count = 0;
$freebonus = 0;
while ($totalamount >= 0)
{
$bcount = 3;
while ($bcount >= 0)
{
if (($bcount == 0) and ($totalamount >= 1))
{
$freebonus = $freebonus + 1;
}

$bcount = $bcount - 1;
$totalamount = $totalamount - 1;
$count = $count + 1; //for testing purposes
}

}

echo "<br><br><H1>\$freebonus is $freebonus<br>";

?>

I tested it, and it adds 1 to $freebonus, for every 4 $totalamount. I think this is what you are asking for..?

-- Zak

<added> I found a minor problem and fixed it...

lZakl

1:58 am on Jan 22, 2005 (gmt 0)

10+ Year Member



mrnoisy, I too made it more difficult than it had to be.. lol, I was sitting and thought "hmmmm if I divided $totalamount by four, and used the floor method to get it down to the 1, without decimals... that would give me the same number! lol I feel pretty dumb...

Heres the code you want:

$totalamount = 232; // just to give us a fun # to work with.
$fbonus = floor($totalamount / 4);
echo "<br><br><H1>\$fbonus is $fbonus<br>";

-- Zak

mrnoisy

2:11 am on Jan 22, 2005 (gmt 0)

10+ Year Member



Thanks lZakl, the second method is perfect. I've never come across the floor function before, very handy.

lZakl

2:23 am on Jan 22, 2005 (gmt 0)

10+ Year Member



For future reference, you may look at ceil also. It does the same thing, but goes UP to the one. So ceil(1.1) would return 2.