Link to home
Start Free TrialLog in
Avatar of jabberwok_e
jabberwok_e

asked on

Better way to write this PHP

I'm looking for a more efficient way to write this PHP code. Here is a portion of it to give you the idea. It covers the 12 months in the calendar year all done in if/else statements. I know there has to be a more efficient way of doing this
 
$date = date("n");
      if (1 <= $date){
            echo '<img src="img/january_c_m.jpg" width="157" height="56" alt="January" />';}
      else{echo '<img src="img/january_b_m.jpg" width="157" height="56" alt="January" />';}
      //feb
      if (2 <= $date){
            echo '<img src="img/feburary_c_m.jpg" width="157" height="56" alt="February" />';}
      else{echo '<img src="img/feburary_b_m.jpg" width="157" height="56" alt="February" />';}
      //mar
      if (3 <= $date){
            echo '<img src="img/march_c_m.jpg" width="157" height="56" alt="March"  />';}
      else{echo '<img src="img/march_b_m.jpg" width="157" height="56" alt="March" />';}
      //apr
      if (4 <= $date){
            echo '<img src="img/april_c_m.jpg" width="157" height="56" alt="April"  />';}
      else{echo '<img src="img/april_b_m.jpg" width="157" height="56" alt="April"  />';}
   etc etc....

Basically I have a calendar page that a visitor can come to. A check is performed to see what month it is and only show color images for that month and any prior months. All other months ahead are to be  black and white images.

So the PHP code does the check and echos out either a color or a black and white image depending on the month when the visitor's visits.

Any help is much appreciated.

Thanks,
Janusz
ASKER CERTIFIED SOLUTION
Avatar of Derokorian
Derokorian
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hi,

better use switch case.
Avatar of xterm
xterm

Derokorian's solution is perfect.
$date = date("n");
$months = array('January','February','March','April','May','June','July','August','September','October','November','December');
for ($i = 0; $i < count($months); $i++) {
	echo '<img src="img/'.strtolower($months[$i]).'_'.( ($i < $date) ? 'c' : 'b').'_m.jpg" width="157" height="56" alt="'.$months[$i].'" />'."\n";
}

Open in new window

I was interrupted and took too long to post. My solution is basically the same as Derokorian's. Sorry.
Ternary... I love ternary but I didn't even think of doing it that way.
Also note mediaman, that $i<count() is proven to be slower than $var = count() ... $i<$var because it has to calculate count each iteration (so if its 10000 value array that's 10000 calls to count). Just an FYI =D
Good point, Derokorian.
Avatar of jabberwok_e

ASKER

Thank you
Thanks Derokorian. I knew there was a more efficient way to do it.