有没有一种简写的方式来写下面的代码?
if (($tstat=='no_prices')&&($l1stat=='no_prices')&&($l2stat=='no_prices')&&($l3stat=='no_prices'))
{
//do something
}
我尝试使用下面的代码,但当其中一个变量不等于'no_prices‘时,它就起作用了。
if (($tstat && $l1stat && $l2stat && $l3stat)=='no_prices')
{
//do something
}
为了检查字符串是否没有引起问题,我尝试用0代替'no_prices‘,用1代替其他值,但结果是一样的。
发布于 2014-03-03 16:08:04
除非我弄错了,否则没有本机的方法可以做到这一点。如果这是您必须经常检查的内容,请尝试对其使用自定义函数,例如:
function allEquals($chkstr, $vals) {
if (!is_array($vals)) { die('allEquals() $vals not an array'); }
foreach ($vals AS $v) {
if ($chkstr != $v) { return false; }
}
return true;
}
发布于 2014-03-03 16:09:18
在您的情况下,您可以执行以下操作:
if (count(array_unique($tstat, $l1stat, $l2stat, $l3stat)) == 1 //Check if all share the same value (i.e., number of unique values is 1
&& $tstat == 'no_prices')) //If everything is the same and $stat == 'no_prices', then everything is 'no_prices'
{
}
发布于 2014-03-03 16:09:26
<?php
$tstat = $l1stat = $l2stat = $l3stat = 'no_prices';
$testVars = array($tstat,$l1stat,$l2stat,$l3stat);
if(count(array_filter($testVars, function($x) { return $x === 'no_prices'; })) == count($testVars))
{
print("Correct");
}
使用带有匿名回调的array_filter,检查其长度是否大于原始数组,即传递的所有条件。
或者如果长度大于零,即传递了任何一个条件
https://stackoverflow.com/questions/22141374
复制相似问题