Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 63 / 68

Checking Balanced Parentheses (an Application of Stacks)

In this lesson you will apply a stack to check that brackets match up, seeing a data structure put to practical use. This is for anyone searching for "PHP balanced parentheses check".

With a stack (last in, first out) you can push opening brackets such as ( and [, then check each closing bracket against whatever is on top. That is how bracket matching works.

The sample code uses the $stack array as a stack: array_push() on an opening bracket, and on a closing one it checks the value from array_pop() against the $pairs associative array to confirm it is the right partner.

A common stumbling block for beginners is the case where the closing bracket is the wrong kind. Matching counts alone is not enough - you have to confirm that each pair is of the right type, and that is the heart of this algorithm.

The same idea is used behind editor auto-completion and code syntax checking. Plenty of similar tools check that HTML opening and closing tags line up correctly.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)