I am using multiple IF statements and like to know how i would put these into an array.
the IF Statements
if ($totalEXP < $l1) echo "1";
if ($totalEXP < $l2) echo "2";
As you can see there the same apart from $l1 and the final echo i would be using around 100 IF statements, Is there a way to put this in an array to save alot of coding?
I know i should be using the ELSEIF statement
<?php
if ($totalEXP < $l1) {
echo "1";
} elseif ($totalEXP < $l2) {
echo "2";
} else {
echo "MAX";
}
?>
but for simplicity reasons i decided the route i had taken.
Sadly i havent tried much to get this working because i dont know if its even possible.
Yes, of course.
You put your level data in an array
$levels = array(
1 => $l1,
2 => $l2,
...
);
And then loop
$pleyer_level = 1;
foreach($levels as $level => $xp)
if($totalEXP > $xp)
$player_level = $level;
It is also smart to put a break in loops when you know their job is done so you don't iterate pointlessly
$pleyer_level = 1;
foreach($levels as $level => $xp)
if($totalEXP > $xp)
$player_level = $level;
else
break;
Not sure this is the best approach, but you could run the if
statements in a for
loop.
for ($i = 1; $i <= 100; $i++) // i increases every new loop
{
if ($totalEXP < ${l$i}) // ${l$i} corresponds to $l1, $l2, $l3 and so on
{
// do stuff
}
}