从具有多个语句的if条件中捕获true语句

时间:2017-04-03 13:19:46

标签: php

如果条件:

,有没有办法从$ this获取真实的声明
$a = 1;
$b = 3;
$c = 7;

if ($a == 3 || $b == 4 || $c == 7) {
    echo "The true statement was: ";
}

我希望得到这个输出:

The true statement was: 7

是否可以在PHP中执行此操作?

或者更好地说我如何检查哪个语句触发了if条件?

5 个答案:

答案 0 :(得分:3)

你不能没有多个条件。无论你得到什么答案,例如:

  • 内联if语句
  • 包装功能
  • 条件
  • 中的条件结果分配
  • 开关
  • 循环

等。总是要求你有多个条件。

如果您不介意多种情况并且只是寻找最优雅的方式来编写它,那就是另一个问题,我们可以提供帮助。

答案 1 :(得分:2)

由于if如何工作,这只能显示1个真实的陈述:

$a = 1;
$b = 3;
$c = 7;

if (($t = $a) ==3 || ($t = $b) == 4 || ($t=$c) == 7) {
   echo "The true statement was: $t";
}

这里发生的是它为每个变量设置$t,然后检查分配结果(值是否)是否成功。由于这是||,因此它会在第一次成功时停止,因此$t将具有最后一次比较值。

答案 2 :(得分:1)

试试这个。

<?php
$day = 1;
$month = 3;
$year = 2017;

$str = "The true statements are: " . ($day == 3 ? "$day, " : "") . ($month == 4 ? "$month, " : "") . ($year == 2017 ? "$year, " : "");
echo substr($str, 0, strlen($str) - 2);
?>

如果我理解正确,这应该有用。

strlen($str) -2将删除尾随&#34;,&#34;。

答案 3 :(得分:1)

以下是布尔变量的解决方案:

$day = 1;
$month = 3;
$year = 2017;

$cday = $day == 3;
$cmonth = $month == 4;
$cyear = $year == 2017;

if ($cday || $cmonth || $cyear) {
    echo "The true statements are: ";
    if($cday) echo "$day<br>\n";
    if($cmonth) echo "$month<br>\n";
    if($cyear) echo "$year<br>\n";
}

答案 4 :(得分:0)

这可能会有所帮助 -

// actual values
$day = 1;
$month = 3;
$year = 2017;

// values & variable names to check
$checks = array(
'day' => 1, 
'month' => 4, 
'year' => 2017,
);
// Loop through the checks
foreach($checks as $check => $value) {
   // compare values
   if($$check == $value) {
       // output and stop looping
       echo "The true statement was: $check -> $value";
       break;
   }
}

Demo

相关问题