我很好奇是否可以在 if 语句中串联一个函数的几种可能性,将它们链接到单个变量并返回有效的变量(如果有)。
以下内容不起作用,但它演示了这个想法。我希望下面的代码返回 2
,因为函数 myFn()
仅在将 2
传递给它时才返回 true。
但是下面的结果返回true: 1
。
if ($b = myFn(1) || $b = myFn(2) || $b = myFn(3)) {
echo 'true: ' . $b;
} else {
echo 'false: ' . $b;
}
function myFn($a) {
if ($a == 2) return $a;
return false;
}
除了添加一系列 elseif
之外,有没有一种方法可以将函数串入一系列 OR
中,同时只返回成功的一个?
最佳答案
只需将每个作业括在括号中即可:
(($b = myFn(1)) || ($b = myFn(2)) || ($b = myFn(3)))
当使用logical时运算符,PHP 将结果强制为 bool 值。如果没有额外的括号,它会回显 '1'
,因为回显会将 true
强制为 '1'
。
使用循环可能会更好:
/**
* Get the first $array value that passes the $test, or else null.
* @return mixed|null
*/
function find ($array, $test) {
foreach ($array as $index => $value) {
if (call_user_func($test, $value, $index, $array))
return $value;
}
}
关于php - 我可以在 if 语句中串联函数并返回单个变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15128217/