mercredi 23 mai 2018

How to convert if/else if into loops

I have the bad habit to write if/else if/ anywhere I can.
I have different type of structure with if/else if/else if.. but I've noticed that it can quickly become hundreds of lines so I want to change this into loops.

This is the first type :

                if($row['event_code'] == 1)
                    $row['event_code'] = 1;
                elseif($row['event_code'] == 4)
                    $row['event_code'] = 2;
                elseif($row['event_code'] == 5)
                    $row['event_code'] = 3;
                elseif($row['event_code'] == 8)
                    $row['event_code'] = 4;
                elseif($row['event_code'] == 9)
                    $row['event_code'] = 5; ...

This is taken from a code where I fetch data from my database.
As you can see the condition can skip numbers but it always assigns a new value with +1.

In the second one I use the new value of the code above and I push into an array the proper color:

foreach($datasetR1 as $value){
                if($value == 1){
                    array_push($intColors, "#82f827");
                }
                elseif($value == 2){
                    array_push($intColors, "#ff4040");
                }
                elseif($value == 3){
                    array_push($intColors, "#31698A");
                } ...

In the last one I put a string depending on a value :

              if (value === 1)
                return 'foo';
              else if (value === 2)
                return 'bar';
              else if (value === 3)
                return 'azerty';
                else if (value === 4)
                return 'qwerty'; ...

What's the best way to write all this ?
Is there a different of speed or is it only better in terms of maintainability to use loops?

Aucun commentaire:

Enregistrer un commentaire