PHP’s switch-statement bit me in the ass

Since a few days a certain operation in the webshop software we’ve written at work was extremely slow. Adding a product to the basket took forever, like 2 minutes. When adding a product to the basket it checks if there are any related products that should be added to the shopping basket as well. This is a feature we’ve called bundles. You can bundle products together and specify some rules such as optional or obligatory to purchase with the selected product.

In our current database some products can have up to 100 optional articles. Such as extended warranties, memory expansion and so forth (in case of e.g. a desktop PC). After finding the source of my problems I was dazzled. I iterated over the products in my shopping basket with a foreach-loop. Inside I used a switch-statement to see if the related article was optional or not. If not, I would simply do a continue to go to the next item in my list. Or so I thought.

This however didn’t seem to work and after looking up PHP’s online manual I found this:

Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

I was very surprised to read this, totally unexpected to learn about this behavior. I really can’t think of any reason why they did this.

PS: I know adding 100 optional products shouldn’t take that long, but since all our prices are pre-calculated (we have a very extended pricing table with lots of features and conditions) we want to be sure the price is right when they add it to the basket so we recalculate it and update the product database.

Scroll to Top