什么是检查多个变量ALL在IF语句中是否等于相同值的简写方法? (PHP)

时间:2021-05-13 22:33:56

Is there a shorthand way of writing the code below?

是否有编写下面代码的简写方法?

if (($tstat=='no_prices')&&($l1stat=='no_prices')&&($l2stat=='no_prices')&&($l3stat=='no_prices'))
{                                   
    //do something
}

I tried using the below code,but it did something when one of the variables was not equal to 'no_prices'.

我尝试使用下面的代码,但是当其中一个变量不等于'no_prices'时,它就做了一些事情。

if (($tstat && $l1stat && $l2stat && $l3stat)=='no_prices')
{
    //do something
}

To check that the strings weren't causing problems I tried substituting 0 for 'no_prices' and 1 for other values, but the result was the same.

为了检查字符串是否没有引起问题,我尝试将0替换为“no_prices”,将1替换为其他值,但结果是相同的。

8 个解决方案

#1


18  

array_flip is several times faster than array_unique:

array_flip比array_unique快几倍:

function all_equal($arr, $value) {
  return array_keys(array_flip($arr)) == array($value);
}

$arr = array($tstat, $l1stat, $l2stat, $l3stat);

echo all_equal($arr, 'no_prices');

A quick profile for the answers given thus far, for 1000 iterations on array length 1000:

到目前为止给出的答案的快速配置文件,对阵列长度1000进行1000次迭代:

  array_flip: 0.07321620 seconds
array_unique: 0.32569408 seconds
     foreach: 0.15136194 seconds
array_filter: 0.41404295 seconds

The code used to profile is here: http://codepad.org/szgNfWHe

用于配置文件的代码在这里:http://codepad.org/szgNfWHe

Note: As @cypherabe rightly points out, array_flip does not overtake array_unique until the array has at least 5 elements, and does not overtake foreach until the array has at least 10 elements.

注意:正如@cypherabe正确指出的那样,array_flip不会超过array_unique直到数组至少有5个元素,并且在数组至少有10个元素之前不会超过foreach。

#2


8  

Unless I'm mistaken, there's no native way of doing this. If this is something that you have to check for often, try using a custom function for it, e.g.:

除非我弄错了,否则没有本土的做法。如果这是您经常需要检查的内容,请尝试使用自定义函数,例如:

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;
}

#3


7  

My first idea would go into PHP's Array API:

我的第一个想法将进入PHP的Array API:

// $tstadt, $l1stat, … are all "no_prices"
$isAllNoPrice = array_unique(array($tstat, $l1stat, …)) == array("no_prices"));
if ($isAllNoPrice) {
    // …

}

Documentation is mandatory otherwise nobody (including yourself) will understand the code.

文档是强制性的,否则任何人(包括您自己)都不会理解代码。

If efficiency might be a concern others pointed out that array_unique() seems to be slow. Using the keys of the hash table would be a next approach:

如果效率可能是一个问题,其他人指出array_unique()似乎很慢。使用哈希表的键将是下一个方法:

// $tstadt, $l1stat, … are all "no_prices"
$varsMap = array(
    $tstat  => null,
    $l1stat => null,
    // …
);
if (array_keys($varsMap) == array("no_prices")) {
    // …

}

But now the wall of code is growing. PHP offers one operator which nearly does what you want and is chainable: &

但现在代码墙正在增长。 PHP提供了一个几乎可以满足你想要的并且可以链接的运算符:&

$v1 = "no_prices";
$v2 = "no_prices";
$v3 = "no_prices";

var_dump(($v1 & $v2 & $v3) == "no_prices"); // bool(true)

$v3 = "prices";
var_dump(($v1 & $v2 & $v3) == "no_prices"); // bool(false)

I said it nearly does what you want: There are cases in which you will have false positives:

我说它几乎可以做你想要的:有些情况下你会有误报:

$v1 = 1;
$v2 = 1;
$v3 = 3;

var_dump(($v1 & $v2 & $v3) == 1); // bool(true)

For Strings it seems to cut the bitmask to the shortest string:

对于字符串,它似乎将位掩码切割为最短的字符串:

$v1 = "abcd";
$v2 = "ab";
$v3 = "abc";

var_dump($v1 & $v2 & $v3); // "ab"
var_dump(($v1 & $v2 & $v3) == "ab"); // bool(true)

So I don't recommend this as a general purpose solution. Only if you know (=unit tested) that your values are in a set where no combination never results to a false positive (e.g. {"dog", "cat", "horse"}) you might consider this solution. I gave it a second thought and must say don't use that at all. Imagine how your colleagues will love you for searching a bug introduced by that method.

所以我不建议将其作为通用解决方案。只有当你知道(=单元测试)你的值在一个集合中,没有任何组合永远不会导致误报(例如{“dog”,“cat”,“horse”})时,你可能会考虑这个解决方案。我给了它第二个想法,必须说不要使用它。想象一下,您的同事将如何爱您搜索该方法引入的错误。

#4


4  

In your case you can do:

在您的情况下,您可以这样做:

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'
{

}

#5


3  

<?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");
}

Use array_filter with a anonymous callback, and check if its length is greater is equal to original array i.e. all conditions passed,

将array_filter与匿名回调一起使用,并检查其长度是否大于原始数组,即所有条件都通过,

or if length is greater than zero i.e. any one condition passed

或者如果长度大于零,即任何一个条件通过

#6


2  

No, this code won't work:

不,这段代码不起作用:

if (($tstat&&$l1stat&&$l2stat&&$l3stat)=='no_prices')
{
    //do something
}

Why? Because condition in parentheses, will check result itself - You are comparing boolean to string. So in pseudo-code, thats what your code looks like:

为什么?因为括号中的条件,将检查结果本身 - 您将布尔值与字符串进行比较。所以在伪代码中,这就是你的代码的样子:

if ( ($tstat is true, $l1stat is true, $l2stat is true, $l3stat is true) == 'no_prices' )
     ^                         whole thing returns true                ^    ^   true  ^

If you wan't to achieve this, you can use count() and array_unique():

如果你不想实现这一点,你可以使用count()和array_unique():

if ($tstat == 'no_prices' && count(array_unique(array($tstat, $l1stat, $l2stat, $l3stat))) == 1)

#7


2  

try this:

$arr = array($tstat,$l1stat,...); //make an array
$arr =array_unique($arr);//unique this array

if(count($arr) == 1 && $arr[0] = 'no_prices'){ // check if only one array element have with same value
    echo "got it";
}

demo example

#8


0  

The answer is "no". There's no shorthand to the given condition that will make your code more readable, which should be your top priority. You can improve it though:

答案是不”。没有给定条件的简写,这将使您的代码更具可读性,这应该是您的首要任务。你可以改进它:

define('MYAPP_NO_PRICES', 'no_prices');

if ($tstat === MYAPP_NO_PRICES
        && $l1stat === MYAPP_NO_PRICES
        && $l2stat === MYAPP_NO_PRICES
        && $l3stat === MYAPP_NO_PRICES) {                                 
    // do something
}

Having all these vars to check individually is a code smell; you might want to rethink this design so you never have to do this.

让所有这些变量单独检查是一种代码气味;你可能想重新考虑这个设计,所以你永远不必这样做。

#1


18  

array_flip is several times faster than array_unique:

array_flip比array_unique快几倍:

function all_equal($arr, $value) {
  return array_keys(array_flip($arr)) == array($value);
}

$arr = array($tstat, $l1stat, $l2stat, $l3stat);

echo all_equal($arr, 'no_prices');

A quick profile for the answers given thus far, for 1000 iterations on array length 1000:

到目前为止给出的答案的快速配置文件,对阵列长度1000进行1000次迭代:

  array_flip: 0.07321620 seconds
array_unique: 0.32569408 seconds
     foreach: 0.15136194 seconds
array_filter: 0.41404295 seconds

The code used to profile is here: http://codepad.org/szgNfWHe

用于配置文件的代码在这里:http://codepad.org/szgNfWHe

Note: As @cypherabe rightly points out, array_flip does not overtake array_unique until the array has at least 5 elements, and does not overtake foreach until the array has at least 10 elements.

注意:正如@cypherabe正确指出的那样,array_flip不会超过array_unique直到数组至少有5个元素,并且在数组至少有10个元素之前不会超过foreach。

#2


8  

Unless I'm mistaken, there's no native way of doing this. If this is something that you have to check for often, try using a custom function for it, e.g.:

除非我弄错了,否则没有本土的做法。如果这是您经常需要检查的内容,请尝试使用自定义函数,例如:

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;
}

#3


7  

My first idea would go into PHP's Array API:

我的第一个想法将进入PHP的Array API:

// $tstadt, $l1stat, … are all "no_prices"
$isAllNoPrice = array_unique(array($tstat, $l1stat, …)) == array("no_prices"));
if ($isAllNoPrice) {
    // …

}

Documentation is mandatory otherwise nobody (including yourself) will understand the code.

文档是强制性的,否则任何人(包括您自己)都不会理解代码。

If efficiency might be a concern others pointed out that array_unique() seems to be slow. Using the keys of the hash table would be a next approach:

如果效率可能是一个问题,其他人指出array_unique()似乎很慢。使用哈希表的键将是下一个方法:

// $tstadt, $l1stat, … are all "no_prices"
$varsMap = array(
    $tstat  => null,
    $l1stat => null,
    // …
);
if (array_keys($varsMap) == array("no_prices")) {
    // …

}

But now the wall of code is growing. PHP offers one operator which nearly does what you want and is chainable: &

但现在代码墙正在增长。 PHP提供了一个几乎可以满足你想要的并且可以链接的运算符:&

$v1 = "no_prices";
$v2 = "no_prices";
$v3 = "no_prices";

var_dump(($v1 & $v2 & $v3) == "no_prices"); // bool(true)

$v3 = "prices";
var_dump(($v1 & $v2 & $v3) == "no_prices"); // bool(false)

I said it nearly does what you want: There are cases in which you will have false positives:

我说它几乎可以做你想要的:有些情况下你会有误报:

$v1 = 1;
$v2 = 1;
$v3 = 3;

var_dump(($v1 & $v2 & $v3) == 1); // bool(true)

For Strings it seems to cut the bitmask to the shortest string:

对于字符串,它似乎将位掩码切割为最短的字符串:

$v1 = "abcd";
$v2 = "ab";
$v3 = "abc";

var_dump($v1 & $v2 & $v3); // "ab"
var_dump(($v1 & $v2 & $v3) == "ab"); // bool(true)

So I don't recommend this as a general purpose solution. Only if you know (=unit tested) that your values are in a set where no combination never results to a false positive (e.g. {"dog", "cat", "horse"}) you might consider this solution. I gave it a second thought and must say don't use that at all. Imagine how your colleagues will love you for searching a bug introduced by that method.

所以我不建议将其作为通用解决方案。只有当你知道(=单元测试)你的值在一个集合中,没有任何组合永远不会导致误报(例如{“dog”,“cat”,“horse”})时,你可能会考虑这个解决方案。我给了它第二个想法,必须说不要使用它。想象一下,您的同事将如何爱您搜索该方法引入的错误。

#4


4  

In your case you can do:

在您的情况下,您可以这样做:

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'
{

}

#5


3  

<?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");
}

Use array_filter with a anonymous callback, and check if its length is greater is equal to original array i.e. all conditions passed,

将array_filter与匿名回调一起使用,并检查其长度是否大于原始数组,即所有条件都通过,

or if length is greater than zero i.e. any one condition passed

或者如果长度大于零,即任何一个条件通过

#6


2  

No, this code won't work:

不,这段代码不起作用:

if (($tstat&&$l1stat&&$l2stat&&$l3stat)=='no_prices')
{
    //do something
}

Why? Because condition in parentheses, will check result itself - You are comparing boolean to string. So in pseudo-code, thats what your code looks like:

为什么?因为括号中的条件,将检查结果本身 - 您将布尔值与字符串进行比较。所以在伪代码中,这就是你的代码的样子:

if ( ($tstat is true, $l1stat is true, $l2stat is true, $l3stat is true) == 'no_prices' )
     ^                         whole thing returns true                ^    ^   true  ^

If you wan't to achieve this, you can use count() and array_unique():

如果你不想实现这一点,你可以使用count()和array_unique():

if ($tstat == 'no_prices' && count(array_unique(array($tstat, $l1stat, $l2stat, $l3stat))) == 1)

#7


2  

try this:

$arr = array($tstat,$l1stat,...); //make an array
$arr =array_unique($arr);//unique this array

if(count($arr) == 1 && $arr[0] = 'no_prices'){ // check if only one array element have with same value
    echo "got it";
}

demo example

#8


0  

The answer is "no". There's no shorthand to the given condition that will make your code more readable, which should be your top priority. You can improve it though:

答案是不”。没有给定条件的简写,这将使您的代码更具可读性,这应该是您的首要任务。你可以改进它:

define('MYAPP_NO_PRICES', 'no_prices');

if ($tstat === MYAPP_NO_PRICES
        && $l1stat === MYAPP_NO_PRICES
        && $l2stat === MYAPP_NO_PRICES
        && $l3stat === MYAPP_NO_PRICES) {                                 
    // do something
}

Having all these vars to check individually is a code smell; you might want to rethink this design so you never have to do this.

让所有这些变量单独检查是一种代码气味;你可能想重新考虑这个设计,所以你永远不必这样做。