条件是有没有办法从$获得真正的声明中,如果条件:捕捉真实的陈述,从如果有多个语句
$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条件?
条件是有没有办法从$获得真正的声明中,如果条件:捕捉真实的陈述,从如果有多个语句
$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条件?
这永远只能显示,因为如何,如果作品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
将具有最后的比较值。
试试这个。
<?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
是删除尾随“,”。
目前还不清楚输出应该是什么 –
据我所知,该声明应该读取一个列表,其中哪些列表触发if语句?有了这个例子,如果有更多的列表,它会列出更多。我认为可以列出多个,因为'echo'使用复数表示“语句”。 – JustCarty
这里是布尔变量的解决方案:
$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";
}
这可能帮助 -
// 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;
}
}
可能有多个检查。如果'$ month == 4'和'$ year == 2017'都是'true'呢?输出是什么? –
我不明白? – Webbanditten
是的,这正是我想得到的....但没有多个ifs里面....是可能的吗? – lewis4u