Created
October 1, 2012 19:11
-
-
Save wesleybliss/3813778 to your computer and use it in GitHub Desktop.
PHP Check If Parentheses Are Balanced
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.