3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php function braceCheck($values) { for ($i = 0; $i <= count($values) - 1; $i++) { $braces = str_split($values[$i]); $values[$i] = isValid($braces); } return $values; } function isValid($braces) { $available = ['{' => '}', '(' => ')', '[' => ']']; $opened = []; $closed = []; for ($i = 0; $i <= count($braces) - 1; $i++) { if (in_array($braces[$i], array_keys($available))) { $opened[] = $braces[$i]; continue; } $closed[] = $braces[$i]; } var_dump($opened, $closed); return match($available, $opened, $closed); } function match($available, $opened, $closed) { $last_open = $opened[count($opened) - 1]; $opened = array_values($opened); $closed = array_values($closed); /* echo 'LAST OPEN: ' . $last_open . PHP_EOL; echo 'AVAILABLE: ' . $available[$last_open] . PHP_EOL; echo 'FIRST CLOSED: ' . $closed[0] . PHP_EOL; */ if (count($opened) !== count($closed)) { echo 'count off'; return 'NO'; } // Check for invalid nesting or non-consecutive braces if ($available[$last_open] !== $closed[0] && $available[$opened[0]] !== $closed[0]) { return 'NO'; } if (count($opened) >= 1) { $result = match( $available, array_slice($opened, 0, -1), array_slice($closed, 1) ); } return 'YES'; } $values = ['{}()[]', '{]}[']; var_dump(braceCheck($values)); ?>
based on Sbgpk
Output for 5.6.30, 7.0.30 - 7.3.0alpha1
array(3) { [0]=> string(1) "{" [1]=> string(1) "(" [2]=> string(1) "[" } array(3) { [0]=> string(1) "}" [1]=> string(1) ")" [2]=> string(1) "]" } array(2) { [0]=> string(1) "{" [1]=> string(1) "[" } array(2) { [0]=> string(1) "]" [1]=> string(1) "}" } Notice: Undefined offset: -1 in /in/OmPjS on line 31 Notice: Undefined index: in /in/OmPjS on line 49 Notice: Undefined offset: 0 in /in/OmPjS on line 49 array(2) { [0]=> string(3) "YES" [1]=> string(3) "YES" }
Output for hhvm-3.22.0
array(3) { [0]=> string(1) "{" [1]=> string(1) "(" [2]=> string(1) "[" } array(3) { [0]=> string(1) "}" [1]=> string(1) ")" [2]=> string(1) "]" } array(2) { [0]=> string(1) "{" [1]=> string(1) "[" } array(2) { [0]=> string(1) "]" [1]=> string(1) "}" } Notice: Undefined index: -1 in /in/OmPjS on line -1 Notice: Undefined index: in /in/OmPjS on line -1 Notice: Undefined index: 0 in /in/OmPjS on line -1 array(2) { [0]=> string(3) "YES" [1]=> string(3) "YES" }
Output for hhvm-3.18.5 - 3.21.3
array(3) { [0]=> string(1) "{" [1]=> string(1) "(" [2]=> string(1) "[" } array(3) { [0]=> string(1) "}" [1]=> string(1) ")" [2]=> string(1) "]" } array(2) { [0]=> string(1) "{" [1]=> string(1) "[" } array(2) { [0]=> string(1) "]" [1]=> string(1) "}" } Notice: Undefined index: -1 in /in/OmPjS on line 31 Notice: Undefined index: in /in/OmPjS on line 49 Notice: Undefined index: 0 in /in/OmPjS on line 49 array(2) { [0]=> string(3) "YES" [1]=> string(3) "YES" }