Open In App

PHP Infix to Postfix Converter

Converting infix expressions to postfix notation (also known as Reverse Polish Notation) is a common task in computer science, especially in the context of parsing and evaluating expressions. In infix notation, the operator is placed between the operands, whereas in postfix notation, the operator follows its operands. In this article, we will explore how to convert an infix expression to a postfix expression in PHP.

Infix to Postfix Converter using Stack

A common approach to convert an infix expression to a postfix expression is to use a stack data structure. The algorithm works as follows:




<?php
 
function getPrecedence($operator) {
    switch ($operator) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
            return 2;
        case '^':
            return 3;
        default:
            return 0;
    }
}
 
function infixToPostfix($infix) {
    $stack = [];
    $postfix = '';
 
    for ($i = 0; $i < strlen($infix); $i++) {
        $char = $infix[$i];
 
        if (ctype_alnum($char)) {
            $postfix .= $char;
        } elseif ($char == '(') {
            array_push($stack, $char);
        } elseif ($char == ')') {
            while (end($stack) != '(') {
                $postfix .= array_pop($stack);
            }
            array_pop($stack);
        } else {
            while (!empty($stack)
                && getPrecedence(end($stack))
                >= getPrecedence($char)) {
                $postfix .= array_pop($stack);
            }
            array_push($stack, $char);
        }
    }
 
    while (!empty($stack)) {
        $postfix .= array_pop($stack);
    }
 
    return $postfix;
}
 
// Driver code
$infix = "a+b*(c^d-e)^(f+g*h)-i";
$postfix = infixToPostfix($infix);
 
echo "Postfix expression: $postfix";
 
?>

Output
Postfix expression: abcd^e-fgh*+^*+i-

Explanation:


Article Tags :