Convert given array to Arithmetic Progression by adding an element | Function to return the number to be added ; If difference of the current consecutive elements is different from the common difference ; If number has already been chosen then it 's not possible  to add another number ; If the current different is twice the common difference then a number can be added midway from current and previous element ; Number has been chosen ; It 's not possible to maintain  the common difference ; Return last element + common difference if no element is chosen and the array is already in AP ; Else return the chosen number ; Driver code
< ? php function getNumToAdd ( $ arr , $ n ) { sort ( $ arr ) ; $ d = $ arr [ 1 ] - $ arr [ 0 ] ; $ numToAdd = -1 ; $ numAdded = false ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) { $ diff = $ arr [ $ i ] - $ arr [ $ i - 1 ] ; if ( $ diff != $ d ) { if ( $ numAdded ) return -1 ; if ( $ diff == 2 * $ d ) { $ numToAdd = $ arr [ $ i ] - $ d ; $ numAdded = true ; } else return -1 ; } } if ( $ numToAdd == -1 ) return ( $ arr [ $ n - 1 ] + $ d ) ; return $ numToAdd ; } $ arr = array ( 1 , 3 , 5 , 7 , 11 , 13 , 15 ) ; $ n = sizeof ( $ arr ) ; echo getNumToAdd ( $ arr , $ n ) ; ? >