Skip to content
Advertisement

Change background color of a cell when next value is different from the preceding one

I’ve been around for years on Stack but this is my first time posting. I’m working on a website (php + mysql) and the following problem is driving me absolutely nuts.

I have a table with 2 columns: Size and Amount. The table is generated by a basic php script simply outputting values stored in the database as rows in the table. Super basic, no fancy stuff there:

JavaScript

The php echo outputs an html table displaying Size and the corresponding available packs (Amount).

JavaScript

Some Sizes are available in different Amounts, so therefore a particular Size can appear multiple times. Example:

JavaScript

What I’m looking to achieve is that rows containing the same Size have the same background color. So it should alternate, grouped by Size, and this is irregular unfortunately. Example:

JavaScript

So if the next Size is different from the preceding one, the row background color should change. This way a single Size is alternately highlighted as a group. Note that Size 2 and 2+ (same for 3 and 3+) are considered to be different sizes, hence the background color should change.

I can’t figure out how to achieve this with php. The difficulty is that I can’t use an evaluation based on odd/even since there sometimes is a “+” involved, making not all Sizes numeric values. Changing the naming scheme to get rid of that “+” is not an option unfortunately.

I was thinking of somehow having php check, while generating the table row by row, if the next outputted Size is identical to the preceding one. If yes: no change in bg-color. If no: change bg-color. However I can’t figure out what the best way is to code something like this. Any pointers in the right direction are much appreciated.

Advertisement

Answer

Just a MCVE:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement