Home > Back-end >  is there a way assign IF statement or Switch Case to a variable
is there a way assign IF statement or Switch Case to a variable

Time:05-07

I am trying assign grades for input integers. But I found it difficult to complete the code. Is there any other way to do the below code such that it will give me desired result?

=========================

$grade = {if($ave>=90 && $ave<100) {
    echo "A";
}
else if ($ave>=60 && $ave<90) {
    echo "B";
}
else {
    echo "F9";
}
return 0;
}

================================

<td><?php echo $fetch['name']?></td>
<td><?php echo $fetch['eng']?></td>
<td><?php echo $fetch['mat']?></td>
<td><?php echo $fetch['lit']?></td>
<td><?php echo $grade ?></td>

The grade will be assigned based on the Average i.e ($ave). I have done the average but the grade is the issue.

CodePudding user response:

This is a classic case for using match, introduced with PHP 8. To evaluate statements (as true or not) and assign values accordingly, we can use match(true) as follows:

$grade = match(true) {
    $ave>=90 && $ave<100 => 'A',
    $ave>=60 && $ave<90 => 'B'
    default => 'F9'
};

If you are yet to upgrade to PHP 8, you can use the switch in its place, which is more verbose, but still cleaner and easier to update than a series of if/elseif/else statements:

switch(true) {
    case $ave>=90 && $ave<100:
        $grade = 'A';
        break;
    case $ave>=60 && $ave<90:
        $grade = 'B';
        break;
    default:
        $grade = 'F9';
        break;
}

Assuming you'll reuse this logic e.g. for grades on different subjects, wrap it in a function:

function get_grade(int $ave): string {
    return match(true) {
        $ave>=90 && $ave<100 => 'A',
        $ave>=60 && $ave<90 => 'B'
        default => 'F9'
    };
}

If you need to use switch, it becomes a bit less verbose inside a function, since you can swap "assign and break" with an immediate return:

function get_grade(int $ave): string {
    switch(true) {
        case $ave>=90 && $ave<100:
            return 'A';
        case $ave>=60 && $ave<90:
            return 'B';
        default: 
            return 'F9';
    }
}

If your averages may also be floats (90.5 etc.), change the function argument signature to a union type declaration int|float instead (also available as of PHP 8).

CodePudding user response:

That might help...

function grade(int $ave)
{
    if ($ave >= 90 && $ave < 100) {
        return 'A';
    }

    if ($ave >= 60 && $ave < 90) {
        return 'B';
    }

    return 'F9';
}

<td><?php echo grade($ave); ?></td>
  • Related