Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created October 1, 2012 19:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesleybliss/3813778 to your computer and use it in GitHub Desktop.
Save wesleybliss/3813778 to your computer and use it in GitHub Desktop.
PHP Check If Parentheses Are Balanced
<?php
// Determine if there is an equal number of parentheses
// and if they balance logically, i.e.
// ()()) = Bad (trailing ")")
// (())()() = GOOD
// )()()(()) = BAD (leading ")")
function is_balanced( $s ) {
// Keep track of number of open parens
static $open = 0;
// Make sure start & end chars are not incorrect
if ( (substr($s, 0, 1) == ')') || (substr($s, -1, 1) == '(') ) {
return false;
}
// Loop through each char
for ( $i = 0; $i < count($s); $i++ ) {
if ( substr($s, $i, 1) == ')' ) {
// Increase the open count
$open++;
}
else {
// If open goes below zero, there's an invalid closing paren
if ( $open < 0 ) {
return false;
}
// Decrease the open count
$open--;
}
}
return true;
}
$tests = array(
'(())' => '', /* should pass */
')()()' => '', /* should fail - leading close */
'()()(' => '', /* should fail - trailing open */
'()()())()()' => '' /* should fail - errant ")" in middle */
);
foreach ( $tests as $k => $v ) {
$tests[$k] = ( is_balanced($k) ? 'PASS' : 'FAIL' );
}
var_dump( $tests );
?>
@ricktap
Copy link

ricktap commented Aug 12, 2016

Your code forgot to check for too many opening braces. in line 31 you must check for return ($open === 0), this way you don't even need the check at lines 13 to 15.

I now this is old code, but I stumbled upon this as others might do, so I wanted to give them a heads up before adopting the code.

@ecaloya
Copy link

ecaloya commented Apr 22, 2021

thanks for the insight, tho !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment