Can someone explain this php function to me?

I think it’s great to look over other people’s code (open-source or with permission that is) to better understand the language. While I understand the down-voting, as google would have been a good resource to figure this out, I’ll try to explain it the best I can.

To help explain it, I have rewritten a bit of your code for you.

function xpToNextLevel($level){

        if($level == 0){
            return 200;
        }

        $d = $level / 98;
        $s = 500;
        $m = 65535 * $d; /* 65535 is equivalent to 0xFFFF */
        $k = $m - $s; /* takes (0xFFFF * ($level / 98)) - $s */
        $dk = $k * $d; /* takes ($m - $s) * ($level/98) */
        $unroundedXP = $dk + $s; /* adds (($m-$s) * ($level/98)) to $s */
        $xp = floor($unroundedXP); /* rounds the experience down. */

        return $xp;
}

so, I know in your comment you asked about the level 4. Let’s trace through that!

4 != 0 // thus we continue.
4/98 = 2/49 /*which is roughly ~0.04082, but for the sake of accuracy, I'll leave it as 2/49 */
65535 * (2/49) = ~2674.89795
2674.89795 - 500 = 2174.89795
2174.89795 * 2/49 = ~88.771345
88.771344 + 500 = 588.771344 //This is the unrounded experience
Experience = 588

The floor function basically rounds to the lowest integer. In positive numbers, this means we take the number and toss out everything behind the decimal point. So the number returned is roughly 588. I say roughly because a computer would be more exact about it.

By the way, I believe this is most comparable to a “Arithmetic Series.” More information about that can be found here: http://mathworld.wolfram.com/ArithmeticSeries.html

Leave a Comment