Showing Text Based on Month

Hi there,

I am wanting to display text based on what month of the year, the below code is what I’ve got, I wanted to check that it’s clean and there aren’t any unnecessary bits of code in it?

<?php $now = new DateTime(); $month = (int)$now->format("m"); if ($month >= 1 AND $month <= 1) { echo "Group B"; } elseif ($month >= 2 AND $month <= 2) { echo "Group A"; } elseif ($month >= 3 AND $month <= 3) { echo "Group B"; } elseif ($month >= 4 AND $month <= 4) { echo "Group A"; } elseif ($month >= 5 AND $month <= 5) { echo "Group B"; } elseif ($month >= 6 AND $month <= 6) { echo "Group A"; } elseif ($month >= 7 AND $month <= 7) { echo "Group B"; } elseif ($month >= 8 AND $month <= 8) { echo "Group B"; } elseif ($month >= 9 AND $month <= 9) { echo "Group A"; } elseif ($month >= 10 AND $month <= 10) { echo "Group B"; } elseif ($month >= 11 AND $month <= 11) { echo "Group A"; } elseif ($month >= 12 AND $month <= 12) { echo "Group B"; }
  1. from a mathematical view:

What result do you expect when checking for larger-or-equal AND lower-or-equal other then the number itself? What should be in between? Why not use an equals condition ===? You already casted to integer, so no floats can be expected.

  1. from a programming view

It’s spaghetti-code. Just use a switch statement for that, or use an array where the month is the key and you assign this group thing to it. Much more readable.

  1. use the code-tags in the forum’s editor

</> (Button)

Nobody wants to read code in one line.

I used that button but it didn’t want to work from my iPhone.

I’m not a programmer so have cobbled together something that seems to work but wanted to run it by someone that knows more.

Don’t write out conditional logic for every possible input value. If all you are doing is mapping input values to output values, either store the data in a database table or an array and simply get the correct output value based on the input.

Sponsor our Newsletter | Privacy Policy | Terms of Service