Skip to content

Instantly share code, notes, and snippets.

@Godefroy
Created September 24, 2012 18:56
Show Gist options
  • Save Godefroy/3777621 to your computer and use it in GitHub Desktop.
Save Godefroy/3777621 to your computer and use it in GitHub Desktop.
Balanced parentheses? in #PHP
<?php
function isBalanced($str){
$count = 0;
$length = strlen($str);
for($i = 0; $i < $length; $i++){
if($str[$i] == '(')
$count += 1;
else if($str[$i] == ')')
$count -= 1;
if($count == -1)
return false;
}
return $count == 0;
}
$list = array("", "(", ")", "()", "(())", "(()", "())", "())(", "(())", "x", "(x", "()x", "x)", "x(y(z))", "x(y)z)(");
foreach($list as $str){
echo $str . " : " . (isBalanced($str) ? "ok" : "ko") . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment