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

后端 未结 10 1117
夕颜
夕颜 2020-12-11 04:59

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 ther

10条回答
  •  我在风中等你
    2020-12-11 05:45

    $range = array(0,1,2,3,4,6,7);    
    // sort just in case the range is not in order
    asort($range);
    $range = array_values($range);
    $indexes = array_keys($range);
    $diff = array_diff($indexes,$range);
    
    echo $diff[0]; // >> will print: 5 
    // if $diff is an empty array - you can print 
    // the "maximum value of the range plus one": $range[count($range)-1]+1
    

提交回复
热议问题