Open In App

PHP Postfix to Infix Converter

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

Postfix to Infix Notation using a Stack

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




<?php
 
function postfixToInfix($postfix) {
    $stack = [];
    $postfix = explode(' ', $postfix);
 
    foreach ($postfix as $token) {
        if (!empty($token)) {
            if (!in_array($token, ['+', '-', '*', '/'])) {
                array_push($stack, $token);
            } else {
                $operand2 = array_pop($stack);
                $operand1 = array_pop($stack);
                 
                $infix = '(' . $operand1 . ' '
                    . $token . ' ' . $operand2 . ')';
                 
                array_push($stack, $infix);
            }
        }
    }
 
    return array_pop($stack);
}
 
// Driver code
$postfix = "3 4 + 2 * 7 /";
$infix = postfixToInfix($postfix);
 
echo "Infix expression: $infix";
 
?>

Output
Infix expression: (((3 + 4) * 2) / 7)

Explanation:


Article Tags :