...

View Full Version : Resolved is there a better way to write this:



Dan13071992
02-01-2012, 10:29 PM
is there a better way to write this instead of having so many if statements? or is it fine how it is?


if ($newchance0 > 100) {
$newchance0 = 100;
}
if ($newchance1 > 100) {
$newchance1 = 100;
}
if ($newchance2 > 100) {
$newchance2 = 100;
}
if ($newchance3 > 100) {
$newchance3 = 100;
}
if ($newchance4 > 100) {
$newchance4 = 100;
}
if ($newchance5 > 100) {
$newchance5 = 100;
}


cheers.

Dan

>ssp-cdr<
02-01-2012, 10:44 PM
Do it like this.


if ($newchance0 > 100) $newchance0 = 100;

if ($newchance1 > 100) $newchance1 = 100;

if ($newchance2 > 100) $newchance2 = 100;

if ($newchance3 > 100) $newchance3 = 100;

if ($newchance4 > 100) $newchance4 = 100;

if ($newchance5 > 100) $newchance5 = 100;


Or use an array.

for ($i = 0; $i < 6; $i++) if ($newchance[$i] > 100) $newchance[$i] = 100;

Fou-Lu
02-01-2012, 11:09 PM
Newchance isn't an array, but you could use a concat and ${'newchance' . $i} instead (or variable variables, which I never recommend).

I'd suggest making an array as well. You could walk the array instead:


$newchance = array(10, 47, 82, 107, 26, ...);
function capChance(&$v, $k, $max = 100)
{
$v = $v > 100 ? $v = 100 : $v;
}
array_walk($newchance, 'capChance');
print_r($newchance);

107 will be capped at 100.

Dan13071992
02-01-2012, 11:10 PM
i believes it was an array as its used like this:

$chance = explode("-", $fetch->crimechance);

Fou-Lu
02-01-2012, 11:23 PM
i believes it was an array as its used like this:

$chance = explode("-", $fetch->crimechance);

$chance here is an array. Not sure what $newchanceX is from though, as those are scalar numbers.

Dan13071992
02-01-2012, 11:24 PM
i was using this:

$newchance5 = $chance[5];

just so i knew what was what at the time of writing my previous part of code

Fou-Lu
02-01-2012, 11:29 PM
Oh yeah, then just use the $chance and either iterate or map for sure. This can be done prior to the creation of the $newchanceX variables if you need to keep them.


I biffed my walk function too. It *should* actually work, but its (IMO) wrong. That should be using just 100, not $v = 100.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum