Last active
January 7, 2024 08:47
-
-
Save AaaRUnnN/a503e3bb48376426e48b5777b3d69b52 to your computer and use it in GitHub Desktop.
PHP Check If Parentheses, Brackets and Braces Are Balanced
This file contains 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 | |
/* PHP Check If Parentheses, Brackets and Braces Are Balanced | |
*/ | |
function hasMatchedParenthesis($string) { | |
$string = str_split($string); | |
$stack = array(); | |
foreach($string as $key=>$value){ | |
switch ($value) { | |
case '(': array_push($stack, 0); break; | |
case ')': | |
if (array_pop($stack) !== 0) | |
return false; | |
break; | |
case '[': array_push($stack, 1); break; | |
case ']': | |
if (array_pop($stack) !== 1) | |
return false; | |
break; | |
default: break; | |
case '{': array_push($stack, 2); break; | |
case '}': | |
if (array_pop($stack) !== 2) | |
return false; | |
break; | |
} | |
} | |
return (empty($stack)); | |
} | |
$check_braces = array( | |
'(())' => '', /* should pass */ | |
'({)}[' => '', /* should fail */ | |
'{{()[]}()}' => '', /* should pass */ | |
'({}])' => '' /* should fail ")*/ | |
); | |
foreach ($check_braces as $key => $value ) { | |
$check_braces[$key] = (hasMatchedParenthesis($key) ? 'PASS' : 'FAIL' ); | |
} | |
echo "<pre>"; | |
print_r($check_braces); | |
echo "</pre>"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
{[{[()]]}} passed, instead of fail