Find the closest greater element for arr [ j ] in the entire array .
$ diff = PHP_INT_MAX ; $ closest = -1 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ arr [ $ i ] < $ arr [ $ j ] && $ arr [ $ j ] - $ arr [ $ i ] < $ diff ) { $ diff = $ arr [ $ j ] - $ arr [ $ i ] ; $ closest = $ j ; } }