PHP 循环显示每天的唯一消息


PHP Loop to display unique message for each day

我有 24 天,每天都有唯一的消息。我如何在某种循环中编写以下 IF 语句以使其更有效率:-

<?
if ($day == '1') {
  $offerTxt = $day1Txt;
} else if ($day == '2') {
  $offerTxt = $day2Txt;
} else if ($day == '3') {
  $offerTxt = $day3Txt;
} else if ($day == '4') {
  $offerTxt = $day4Txt;
} else if ($day == '5') {
  $offerTxt = $day5Txt;
} else if ($day == '6') {
  $offerTxt = $day6Txt;
} 

?>

您可以像这样内联执行此操作:

$offerTxt = ${'day'.$day.'Txt'};

您可能应该检查日期是否在某个集合中,因此您的代码将如下所示:

$daysUsed = array(1,2,3,4,5,6);
$offerTxt = '';
if(in_array((int)$day, $daysUsed)) {
    $offerTxt = ${'day'.$day.'Txt'};
}

您可以使用数组:

$array = $textforDays = array(
    1 => 'Text for day 1',
    2 => 'Text for day 2',
    3 => 'Text for day 3',
    4 => 'Text for day 4',
    5 => 'Text for day 5',
    6 => 'Text for day 6',
);
echo $textforDays[$day];