control-structure

Can the for loop be eliminated from this piece of PHP code?

二次信任 提交于 2019-11-27 06:54:49
问题 I have a range of whole numbers that might or might not have some numbers missing. Is it possible to find the smallest missing number without using a loop structure? If there are no missing numbers, the function should return the maximum value of the range plus one. This is how I solved it using a for loop: $range = [0,1,2,3,4,6,7]; // sort just in case the range is not in order asort($range); $range = array_values($range); $first = true; for ($x = 0; $x < count($range); $x++) { // don't

Does the last element in a loop deserve a separate treatment?

本秂侑毒 提交于 2019-11-27 02:36:53
问题 When reviewing, I sometimes encounter this kind of loop: i = begin while ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i } Then I ask the question: would you write this? i = begin mid = ( end - begin ) / 2 // (the middle element) while ( i != end ) { // ... do stuff if ( i > mid ) { ... do other stuff } increment i } In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done

for loop vs while loop vs foreach loop PHP

淺唱寂寞╮ 提交于 2019-11-26 09:51:43
问题 1st off I\'m new to PHP. I have been using for loop,while loop,foreach loop in scripts. I wonder which one is better for performance? what\'s the criteria to select a loop? which should be used when we loop inside another loop? the code which I\'m stuck with wondering which loop to be used. for($i=0;$i<count($all);$i++) { //do some tasks here for($j=0;$j<count($rows);$j++) { //do some other tasks here } } It\'s pretty obvious that I can write the above code using while. Hope someone will help