Solve the Linear Equation of Single Variable | Function to solve the given equation ; Traverse the equation ; For cases such as : x , - x , + x ; Flip sign once ' = ' is seen ; There may be a number left in the end ; For infinite solutions ; For no solution ; x = total sum / coeff of x ' - ' sign indicates moving numeric value to right hand side ; Driver code
< ? php function solveEquation ( $ equation ) { $ n = strlen ( $ equation ) ; $ sign = 1 ; $ coeff = 0 ; $ total = 0 ; $ i = 0 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ equation [ $ j ] == ' + ' $ equation [ $ j ] == ' - ' ) { if ( $ j > $ i ) $ total += $ sign * intval ( substr ( $ equation , $ i , $ j - $ i ) ) ; $ i = $ j ; } else if ( $ equation [ $ j ] == ' x ' ) { if ( ( $ i == $ j ) $ equation [ $ j - 1 ] == ' + ' ) $ coeff += $ sign ; else if ( $ equation [ $ j - 1 ] == ' - ' ) $ coeff -= $ sign ; else $ coeff += $ sign * intval ( substr ( $ equation , $ i , $ j - $ i ) ) ; $ i = $ j + 1 ; } else if ( $ equation [ $ j ] == ' = ' ) { if ( $ j > $ i ) $ total += $ sign * intval ( substr ( $ equation , $ i , $ j - $ i ) ) ; $ sign = -1 ; $ i = $ j + 1 ; } } if ( $ i < $ n ) $ total += $ sign * intval ( substr ( $ equation , $ i ) ) ; if ( $ coeff == 0 && $ total == 0 ) return " Infinite ▁ solutions " ; if ( $ coeff == 0 && $ total ) return " No ▁ solution " ; $ ans = - $ total / $ coeff ; return " x ▁ = ▁ " . $ ans ; } $ equation = " x + 5-3 + x = 6 + x - 2" ; echo ( solveEquation ( $ equation ) ) ; ? >