Skip to content

PHP: Check if parentheses are balanced

function isParenthesisMatching($string) {
    $openingClosingMatchSymbols = ['(' => ')', '{' => '}', '[' => ']'];
    $closingSymbolOpeningMatch = array_flip($openingClosingMatchSymbols);
    $stack = [];
    for($i=0, $c = strlen($string); $i < $c; $i++) {
        $char = $string[$i];
        if(array_key_exists($char, $openingClosingMatchSymbols)) {
            array_push($stack, $char);
        } else {
            if(count($stack) === 0) {
                return false;
            } 
            else if($closingSymbolOpeningMatch[$char] === end($stack)) {
                array_pop($stack);
            } 
        }
    }
    return empty($stack);
}
$string = "{[({})]}";
var_dump(isParenthesisMatching($string));
$string = "[{{}}]]";
var_dump(isParenthesisMatching($string));
$string = "[]]";
var_dump(isParenthesisMatching($string));
$string = "[{{}";
var_dump(isParenthesisMatching($string));
$string = "[]";
var_dump(isParenthesisMatching($string));

// ouput:
// bool(true) 
// bool(false)
// bool(false)
// bool(false)
// bool(true) 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments