Longest Common Prefix Matching | Set | A Utility Function to find the common prefix between first and last strings ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; sorts the N set of strings ; prints the common prefix of the first and the last string of the set of strings ; Driver Code
< ? php function commonPrefixUtil ( $ str1 , $ str2 ) { $ result = " " ; $ n1 = strlen ( $ str1 ) ; $ n2 = strlen ( $ str2 ) ; for ( $ i = 0 , $ j = 0 ; $ i <= $ n1 - 1 && $ j <= $ n2 - 1 ; $ i ++ , $ j ++ ) { if ( $ str1 [ $ i ] != $ str2 [ $ j ] ) break ; $ result = $ result . $ str1 [ $ i ] ; } return ( $ result ) ; } function commonPrefix ( & $ arr , $ n ) { sort ( $ arr ) ; echo commonPrefixUtil ( $ arr [ 0 ] , $ arr [ $ n - 1 ] ) ; } $ arr = array ( " geeksforgeeks " , " geeks " , " geek " , " geezer " ) ; $ n = sizeof ( $ arr ) ; commonPrefix ( $ arr , $ n ) ; ? >