如何根据其他变量设置的条件设置变量值

时间:2015-11-11 23:40:25

标签: php

所以我是PHP的新手,我目前正在做一个小项目作为练习,我已经设法得到了几行代码而没有摔倒......但是我有点卡在这里。

基本上,我的脚本目前所做的是检查我设置的三个不同的变量(每个都是一个真/假选项)并区分是否只选择了一个真实选项(在3个选项中,只有一个可以为真,其他2必须是假的)。如果只有1个值设置为true,则其余代码运行;如果多个值设置为true,或者没有值设置为true,则会显示用户的错误提示。

完成此检查之后,我想根据链接到相关变量的记录设置$ name的值,例如,这是我提出的,但它没有似乎工作......

  

if($ value1 ==“true”){$ name = $ result1;}

     

else if($ value2 ==“true”){$ name = $ result2;}

     

else if($ value3 ==“true”){$ name = $ result3;}

     

否则退出(0)

所以我基本上想要通过识别3个值变量中的哪一个为真来设置$ name变量,然后使用$ result中检索到的相关变量设置$ name

任何帮助将不胜感激。在任何人开始之前...我知道我可能听起来有点疯狂......但我们都必须从某个地方开始!!

由于

2 个答案:

答案 0 :(得分:2)

使用开关看起来会更好:

switch(true){
   case $value1:
      $name = $result1;
      break;
   case $value2:
      $name = $result2;
      break;
   case $value3:
      $name = $result3;
      break;
   default:
      exit();
}

如果您需要确保只有其中一个陈述为真,请在使用此前验证:

//In case you need to make there is only a single true statement
$found = false;
for($i=1; $i<4; $i++) {
   $value = "value".$i;
   if($$value) {
      if($found) {
          exit("More than one 'true' statement");
      }
      $found = true;
   }
}

答案 1 :(得分:0)

Dracony的答案看起来确实不错,但是当多个值设置为true时会失败。为了获得更大的灵活性,您应该将值映射到数组中,并使用标记变量跟踪状态(值为true的数量)。找到满足以下所有条件的完全注释的示例。此外,此代码适用于任何长度的数组(您可以通过在$values$results中添加更多值来添加条件。)

// store the data in arrays for easier manipulation
$values = array($value1, $value2, $value3);
$results = array($result1, $result2, $result3);

// set a flag to check the state of the condition inside the loop
// it keeps track of the index for which the value is true
$flag = -1;
$name = NULL;

// use for and not foreach so we can easily track index
for ($i = 0; $i < count($values); $i++) {
  // if no index has been found 'true' yet, assign the current result.
  if ($values[$i] === true) {
    if ($flag === -1) {
      $flag = $i;
      $name = $results[$i];
    }
    // if a 'true' value has been found for another index
    // reset the name var & stop the loop
    if ($flag > -1 && $flag !== $i) {
      $name = NULL;
      break;
    }
  }   
}

if ($name) {
  // run code when only 1 value is true
} else {
  exit();
}
相关问题