HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpModerate

Shorter way to write multiple if-then-else-if

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
elsewaywritemultiplethenshorter

Problem

if($row['best']){
    $id = $row['best'];
} elseif($row['average']){
    $id = $row['average'];
} elseif($row['bad']){
    $id = $row['bad'];
}


If row['best'] is null, I need $id to equal the 2nd best. If 2nd best is null, $id is equal to the next best.

Solution

Simon has already answered while I was writing something similar:

foreach(array('best', 'average', 'bad') as $rank) {
  if($row[$rank]) {
    $id = $row[$rank];
    break;
  }
}


Note however, that in both this and Simon's answer, there is a possibility of $id never being assigned a value. Konijn's answer avoids that (although $id might still end up false'y)

Code Snippets

foreach(array('best', 'average', 'bad') as $rank) {
  if($row[$rank]) {
    $id = $row[$rank];
    break;
  }
}

Context

StackExchange Code Review Q#45865, answer score: 10

Revisions (0)

No revisions yet.