Find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Sort the elements ; Now fix the first element one by one and find the other two elements ; To find the other two elements , start two index variables from two corners of the array and move them toward each other index of the first element ; in the remaining elements index of the last element ; A [ i ] + A [ l ] + A [ r ] > sum ; If we reach here , then no triplet was found ; Driver Code
< ? php function find3Numbers ( $ A , $ arr_size , $ sum ) { $ l ; $ r ; sort ( $ A ) ; for ( $ i = 0 ; $ i < $ arr_size - 2 ; $ i ++ ) { $ l = $ i + 1 ; $ r = $ arr_size - 1 ; while ( $ l < $ r ) { if ( $ A [ $ i ] + $ A [ $ l ] + $ A [ $ r ] == $ sum ) { echo " Triplet ▁ is ▁ " , $ A [ $ i ] , " ▁ " , $ A [ $ l ] , " ▁ " , $ A [ $ r ] , " STRNEWLINE " ; return true ; } else if ( $ A [ $ i ] + $ A [ $ l ] + $ A [ $ r ] < $ sum ) $ l ++ ; else $ r -- ; } } return false ; } $ A = array ( 1 , 4 , 45 , 6 , 10 , 8 ) ; $ sum = 22 ; $ arr_size = sizeof ( $ A ) ; find3Numbers ( $ A , $ arr_size , $ sum ) ; ? >