Skip to content

Instantly share code, notes, and snippets.

@AaaRUnnN
Last active January 7, 2024 08:47
Show Gist options
  • Save AaaRUnnN/a503e3bb48376426e48b5777b3d69b52 to your computer and use it in GitHub Desktop.
Save AaaRUnnN/a503e3bb48376426e48b5777b3d69b52 to your computer and use it in GitHub Desktop.
PHP Check If Parentheses, Brackets and Braces Are Balanced
<?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>";
?>
@Looden
Copy link

Looden commented Jul 7, 2022

{[{[()]]}} passed, instead of fail

@AaaRUnnN
Copy link
Author

AaaRUnnN commented Jul 8, 2022

@Looden my compiler {[{[()]]}} return FALSE

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