php - How to optimize an if else if statement where previous ifs are not used in loop? -


this hypothetical code, assuming have following:

let's have array , has lots of data, integers in sample question, can type of data that's sorted in fashion in regards if statements.

$a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,...,9,9,9); 

let's have loop numerous if else if statements, , can have criteria doing something.

for($i=0; i<count($a); i++) {     // these if statements can , may or may not related $a     if($a[$i] == 0 && $i < 10) {          //     }     else if($a[$i] == 1 && $i < 20) {         //     }     else if($a[$i] == 2) {         //     }     else if($a[$i] == 3) {         //     }      // , on } 

now question, after first if statement iterations done, it's never used. once loop starts using next if statement, previous if statement(s) don't need evaluated again. can use first if statement n amount of times , on , forth.

is there way optimize doesn't have go through previous if else if statements it's looping through data? mind, data can anything, , if statements can variety of conditions.

is there paradigm shift, don't see, required on how should coded provide optimal performance?

you leverage call_user_func_array. need build class stored methods call perform statements. consider class this:

class mystatements {     public function if0($a, $i) {         if($a[$i] == 0 && $i < 10) {             //         }     }      public function if1($a, $i) {         if($a[$i] == 1 && $i < 20) {             //         }     } } 

you this:

$stmts = new mystatements(); for($i = 0; < count($a); i++) {     call_user_func_array(array($stmts, 'if' . strval($i)), array($a, $i)); } 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -