webnat0
webnat0

Reputation: 2716

How can I make this code simpler?

if(condition 1){
 var=changeVar(var);
 changed=true;
}

if(condition 2){
 var=changeVar2(var);
 changed=true;
}

if(condition 3){
 var=changeVar3(var);
 changed=true;
}

I don't like how changed=true; is repeated three times.

Upvotes: 4

Views: 135

Answers (5)

Nanne
Nanne

Reputation: 64399

You could save the old var, and compare it?

oldVar = var;

//your code here.

changed = (oldVar != var);

I had == in there at first, but wouldn't that give a wrong (or at least different) sollution then in the question?

Upvotes: 7

AndersTornkvist
AndersTornkvist

Reputation: 2629

<?php
if (condition 1) {
    var=changeVar(var);
}
if (condition 2) {
    var=changeVar2(var);
}
if (condition 3) {
    var=changeVar3(var);
}
changed=(condition 1||condition 2||condition 3||changed); // set changed value only if condition 1, condition 2 or condition 3 is true, keep old value otherwise
?>

Upvotes: 2

Ferguzz
Ferguzz

Reputation: 6087

if(condition1||condition2||condition3) {
    switch(condition) {
        case 1: var = changeVar(var);
        break;
        case 2: var = changeVar2(var);
        break;
        case 3: var = changeVar3(var);
        break;
    }
    changed = true;
}

Upvotes: -1

ashein
ashein

Reputation: 487

$changed = true;
if ($cond1) {}
elseif ($cond2) {}
else { $changed = false; }

Upvotes: 1

rid
rid

Reputation: 63442

if (condition 1 || condition 2 || condition 3) {
    if (condition 1) {
        var = changeVar(var);
    }
    if (condition 2) {
        var = changeVar2(var);
    }
    if (condition 3) {
        var = changeVar3(var);
    }
    changed = true;
}

Upvotes: 1

Related Questions