问题描述:

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";

网友答案:
$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.

网友答案:

Use an array:

$days_of_week = array(
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday");

echo $days_of_week[$d]
网友答案:
echo date ('l');

As per the PHP manpage

l (lowercase 'L'): A full textual representation of the day of the week

网友答案:

There are multiple ways of doing this:


1. You can just use l in date (lowercase L):

echo date('l');


2. You could use an array:

$days = array(
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday");

and then access it with:

echo $days[$d];


3. You can use a switch:

switch ($d)
{
    case 0:
        echo "Sunday";
    ...
}

however, I tend to avoid switch statements as they are the hardest for the human brain to comprehend.


Some tips:

  1. You misspelled Tuesday
  2. Use else if instead of multiple ifs.
网友答案:

You could always look into the switch statement, something like:

$d=date('w');
switch($d) {
    case(0):
        $day='Sunday';
        break;
    case(1):
        $day='Monday';
        break;
    case(2):
        $day='Tuesday';
        break;
    case(3):
        $day='Wednesday';
        break;
    case(4):
        $day='Thursday';
        break;
    case(5):
        $day='Friday';
        break;
    case(6):
        $day='Saturday';
        break;
    default:
        $day=null;
}
if($day!==null) {echo($day);}
相关阅读:
Top