在PHP中编写大型elseif语句的简单方法

时间:2012-04-29 04:25:18

标签: php html

我从电子邮件表单中获取帖子值,并将所有选项值设置为数字,我正在尝试将它们转换为实际字符串以通过电子邮件发送。我需要使这个代码更容易使用。

if ($subject == "1") {
$sub = "General Questions"; 
} elseif($subject == "2") {
$sub = "Membership";
} elseif($subject == "3") {
    $sub = "Club Fees";
} elseif($subject == "4") {
    $sub = "Proshop & Lessons";
} elseif($subject == "5") {
    $sub = "Events"; 
} elseif($subject == "6") {
    $sub == "Leagues & Programs";
} elseif($subject == "7") {
    $sub == "Resturant & Bar";
};

也许我可以将value=''设置为实际值并一起跳过这部分。

4 个答案:

答案 0 :(得分:8)

为什么不制作一个关联数组?

$subs = array(
  1 => 'General Questions',
  2 => 'Membership',
  3 => 'Club Fees',
  4 => 'Proshop & Lessons',
  // others.
);

$sub = isset($subs[$subject]) ? $subs[$subject] : 'Default Value';

答案 1 :(得分:4)

重写的一种方法是在PHP中使用switch语句。你可以read more about it here

答案 2 :(得分:3)

使用switch语句,或将潜在结果映射到各自的值:

switch ( $subject ) {
  case 1:
    $sub = 'foo';
    break;
  case 2:
    $sub = 'bar';
    break;
}

或者

$values = array( "Foo", "bar" );
$sub = $values[ --$subject ];

答案 3 :(得分:3)

试试这个

<?php
switch ($subject)
{
case "1":
  $sub = "General Questions";
  break;
case "2":
  $sub = "Membership";
  break;
case "3":
  $sub = "Club Fees";
  break;
case "4":
  $sub = "Proshop &amp; Lessons";
  break;
case "5":
  $sub = "Events";
  break;
case "6":
  $sub = "Leagues &amp; Programs";
  break;
case "6":
  $sub = "Resturant &amp; Bar";
  break;
default:
  $sub = "";
}
?>