Search code examples
phpif-statementdayofweek

Avoiding if statements when displaying content based on weekdays (PHP)


Is there a reason or a way to avoid if statements in a situation like this where I need to display content based on which day of the week it is?

$d=date("w");
if ($d=="0") echo "Sunday";
if ($d=="1") echo "Monday";
if ($d=="2") echo "Tueday";
if ($d=="3") echo "Wednesday";
if ($d=="4") echo "Thursday";
if ($d=="5") echo "Friday";
if ($d=="6") echo "Saturday";

Solution

  • $dates = array("Sunday",
                   "Monday",
                   "Tuesday",
                   "Wednesday",
                   "Thursday",
                   "Friday",
                   "Saturday"
                  );
    
    echo $dates[date("w")];
    

    That should word nicely.

    EDIT: Come to think of it, just using echo date("l") should work just fine for your purposes.