Elements to be added so that all elements of a range are present in array | Function to count numbers to be added ; Sort the array ; Check if elements are consecutive or not . If not , update count ; Driver code
< ? php function countNum ( $ arr , $ n ) { $ count = 0 ; sort ( $ arr ) ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) if ( $ arr [ $ i ] != $ arr [ $ i + 1 ] && $ arr [ $ i ] != $ arr [ $ i + 1 ] - 1 ) $ count += $ arr [ $ i + 1 ] - $ arr [ $ i ] - 1 ; return $ count ; } $ arr = array ( 3 , 5 , 8 , 6 ) ; $ n = count ( $ arr ) ; echo countNum ( $ arr , $ n ) ; ? >