views:

62

answers:

1
$arr = $results->row();
$score = 0;
foreach ($arr as &$i) {
    switch($i){
        case ($i <= 4 AND $i >= 1):
            $score += 1;
            break;
        case ($i < 8 AND $i > 4):
            $score += 3;
            break;
        case ($i >= 8):
            $score += .5;
            break;
    }
}
    echo $score

This is my current code that adds up a total value based on about 30 db (SQL) entries. Kind of like a grading ruberik. I need help improving the above code. Is there a better way to do this?

Also. Some of these (ie, rows 3,5,8 need to be scored differently.) How do I omit these rows in this logic and pass them to be scored differently?

This is a codeigniter function, so I'd love it if somebody could show me a quick easy, pretty way to do this! Thanks a lot!

+1  A: 

Minor improvements can be made but nothing drastic.

  • Simply using if/else instead of switch case can slightly improve speed.
  • Determine which of the cases is going to occur the most often and place it first, as this will reduce the number of cases needed to be hit for each iteration.
  • Create an array of any iterations you wish to skip for an easy isset call as opposed to checking for each case (multiple if/else statements would be required)
  • Keep track of the number of iterations for skipping those rows

$skip_iterations = array(3 => 1, 5 => 1, 8 => 1);
$arr = $results->row();
$score = 0;
$i = 1;
foreach ($arr as &$a) {
    // skip rows 3, 5, and 8
    if (isset($skip_iterations[$i++])) 
        continue;
    if ($a >= 1 && $a <= 4) {
        $score += 1;
    } else if ($a > 4 && $a < 8) {
        $score += 3;
    } else if ($a > 8) {
        $score += .5;
    }
}
echo $score;
cballou
This looks pretty good. If I wanted to create 4 cases (different scoring methods) how would I switch those around?
Kevin Brown
You'd simply want to add another `else if` clause and the ordering is up to you. Simply place them in an order of decreasing frequency based on what your user's are generally selecting for answers.
cballou
I think we're not communicating...I mean, If I wanted multiple scoring methods, how would I do that?ie. I want to score 2,4,5,6,20 one way, and 3,7,9 another way, and skip 1,10?
Kevin Brown
Starting a new topic to improve your answer...
Kevin Brown