Open In App

PHP Postfix to Infix Converter

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Initialize an empty stack.
  • Iterate through each element of the postfix expression.
  • If the element is an operand, push it onto the stack.
  • If the element is an operator, pop two operands from the stack, combine them with the operator in between (in the form operand1 operator operand2), and push the resulting expression back onto the stack.
  • After processing all elements, the stack should contain only one element, which is the final infix expression.

PHP




<?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:

  • The postfixToInfix() function takes a postfix expression as input and splits it into tokens using spaces as delimiters.
  • It iterates through each token, pushing operands onto the stack and combining the top two operands with the operator when an operator is encountered.
  • Parentheses are added to ensure the correct order of operations in the resulting infix expression.
  • The final infix expression is obtained by popping the last element from the stack.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads