对于循环变量,混淆了单引号和双引号

时间:2013-07-03 00:16:01

标签: php variables for-loop

我想将以下代码设为for循环以使所有内容都更好,但我似乎无法正确获取引号并最终得到一个空白页

if ($_POST['week'])
{
  $week = $_POST['week'];
}
//or check for a value submitted by the week menu
elseif ($_POST["user_week1"] == "week1") {
  $week = "1";
}
elseif ($_POST["user_week2"] == "week2") {
  $week = "2";
}
else if ($_POST["user_week3"] == "week3") {
  $week = "3";
}
else if ($_POST["user_week4"] == "week4") {
  $week = "4";
}
else if ($_POST["user_week5"] == "week5") {
  $week = "5";
}
else if ($_POST["user_week6"] == "week6") {
  $week = "6";
}
else {
  $week = "1";
}

我试着这样做:

if ($_POST['week'])
{
  $week = $_POST['week'];
}
for ($i = 1; $i<7; $i++)
{
  else if ($_POST["user_week'.$i.'"] == "week'.$i.'") {
    $week = $i;
}
}
else {
  $week = "1";
}

但是这样做不太顺利,我尝试使用双引号而不是围绕变量使用单引号加上“”和“无效”。

任何人都可以帮忙解决这个问题吗,还是指出一个关于变量的单引号和双引号的良好资源?

2 个答案:

答案 0 :(得分:1)

你是否都在意识到else if不在那里的事实!?

您应该做的是以下

$week = "1";
if ($_POST['week']) {
  $week = $_POST['week'];
} else {
  for ($i = 1; $i < 7; $i++) {
    if ($_POST["user_week" . $i] == "week" . $i) {
      $week = $i;
      break;
    }
  }
}

答案 1 :(得分:-1)

  elseif ($_POST['user_week' . $i] == 'week' . $i) 

以上修正应该有效