Ok, so maybe this is common knowledge, but I still felt a little clever when I figured out this trick. The situation was that I wanted to test a bunch of different conditions to figure out which time category a date falls into. It would be fairly simple to do with a bunch of if…then…else’s, but really ugly. Here’s the trick I came up with…use switch(true), and then set up your cases to evaluate to true or false. Here’s some example code:
$mymd = date('Ymd', $row->date_due); $tymd = date('Ymd'); //Today switch (true) { case $mymd == $tymd : $ind = "today"; break; case $mymd < $tymd : $ind = "overdue"; break; case $mymd < ($tymd + (6 - date('w'))) : $ind = "restofweek"; break; default : $ind = (int) date('Ym',$row['duedate']); break; }
Comments are closed.