Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this code simpler?

Tags:

php

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.

like image 645
webnat0 Avatar asked Dec 28 '22 20:12

webnat0


2 Answers

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?

like image 170
Nanne Avatar answered Dec 30 '22 10:12

Nanne


<?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
?>
like image 26
AndersTornkvist Avatar answered Dec 30 '22 11:12

AndersTornkvist