...

View Full Version : Resolved PHP Level system with user XP



mrkfc
02-17-2012, 09:28 PM
This is my code:


<?php
if ($userexp > 50) {
$sfl_level="1";
}else if ($userexp > 75){
$sfl_level = "2";
} else {
$sfl_level = "0";
}
?>


I am attempting to develop a user level system for my site, users already have an exp value stored in the database. I am wanting to make some code which gives people a level depending on how much xp they have. For example if they have more than 50 xp they become level 1 and if they have more than 75 xp they will become level 2. When I have attempted to use this system a user with 90 xp is only given a level of 1 instead of 2.

I need to find a way to make all the levels seperate and work properly, and I want people with less than 50 xp to be level zero.

Any help with this would be greatly appreciated,
Thank you :)

Fou-Lu
02-17-2012, 10:02 PM
The problem is this if. If you have 100, 100 is > 50, so the first if branch applies, not the else if or the else. When seeking a > check, start at the top down.
The better solution is to write an algorithm to calculate the end $sfl_level based on the provided $userexp instead of using hardcoded numbers. This takes some trig knowledge to do properly if you want to avoid linear growth (which with exp would tell me that you are looking for each level being more difficult to obtain than the previous, although the numbers you have here indicate that the amount requires is reduced as levels increase).

thelung
02-18-2012, 12:30 AM
This looks like something I would use a switch statement for.
http://www.w3schools.com/php/php_switch.asp
:thumbsup:

felgall
02-18-2012, 12:33 AM
Put the if tests in descending order (no need for a switch statement as that would need to add a second test for each value to provide the other end of the range)


<?php
if ($userexp > 75) {
$sfl_level="2";
}else if ($userexp > 50){
$sfl_level = "1";
} else {
$sfl_level = "0";
}
?>

mrkfc
02-18-2012, 12:47 AM
Thank you :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum