Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite a PHP function with arrays instead

Is there any way I could rewrite this function with an array instead of all these if statements? Could i maybe use some for loop together with an array? How would that look like? Any suggestions of simpler code?

Here is my php function:

function to_next_level($point) {

    /*
    **********************************************************************
    *
    *   This function check how much points user has achievents and how much procent it is until next level
    *
    **********************************************************************
    */

    $firstlevel = "3000";
    $secondlevel = "7000";
    $thirdlevel = "15000";
    $forthlevel = "28000";
    $fifthlevel = "45000";
    $sixthlevel = "80000"; 

    if($point <= $firstlevel) {

        $total = ($point/$firstlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;

    } elseif ($point <= $secondlevel) {

        $total = ($point/$secondlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $thirdlevel) {

        $total = ($point/$thirdlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $forthlevel) {

        $total = ($point/$forthlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $fifthlevel) {

        $total = ($point/$fifthlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $sixthlevel) {

        $total = ($point/$sixthlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    }


}
like image 618
Mensur Avatar asked Feb 23 '26 05:02

Mensur


1 Answers

Try this:

function to_next_level($point) {

    /*
    **********************************************************************
    *
    *   This function check how much points user has achievents and how much procent it is until next level
    *
    **********************************************************************
    */

    $levelArray = array(3000, 7000, 15000, 28000, 45000, 80000);
    foreach ($levelArray as $level) 
    {
        if ($point <= $level) {
            $total = ($point/$level) * 100;
            $remaining =  round($total);  

            //echo number_format($remaining, 0, '.', ' ');
            return $remaining;            
        }
    }

}
like image 99
arbogastes Avatar answered Feb 25 '26 19:02

arbogastes