简体   繁体   English

检查多个变量,如果设置而不是 0

[英]Check multiple variables if set and not 0

I have multiple variables and i need to check if all of these variables are set or not "0".我有多个变量,我需要检查所有这些变量是否都设置为“0”。 So all of these variables need to have a value.所以所有这些变量都需要有一个值。

The values i get from WordPress ACF:我从 WordPress ACF 获得的值:

$p1 = get_field( "wert", $s1 );
$p2 = get_field( "wert", $s2 );
$p3 = get_field( "wert", $s3 );
$p4 = get_field( "wert", $s4 );
$p5 = get_field( "wert", $s5 );
$p6 = get_field( "wert", $s6 );
$p7 = get_field( "wert", $s7 );
$p8 = get_field( "wert", $s8 );
$p9 = get_field( "wert", $s9 );
$p10 = get_field( "wert", $s10 );

No i need to check if all of them have a value.不,我需要检查它们是否都有价值。 I do this with an if statement:我用 if 语句来做到这一点:

if($s1 && $s2 && $s3 && $s4 && $s5 && $s6 && $s7 && $s8 && $s9 && $s10) {
   // MY CODE
}

But when i do this i still execute the script when one of the variables is "0".但是当我这样做时,当变量之一为“0”时,我仍然执行脚本。 How can i check this as short as possible?我怎样才能检查这个尽可能短?

Thank you so much!太感谢了!

Your check is checking the $s variables and this is not the value of the fields, which are stored in $p variables.您的检查是检查 $s 变量,这不是存储在 $p 变量中的字段的值。

You can convert variables to array, and check with in_array:您可以将变量转换为数组,并使用 in_array 进行检查:

$p1 = get_field( "wert", $s1 );
$p2 = get_field( "wert", $s2 );
$p3 = get_field( "wert", $s3 );
$p4 = get_field( "wert", $s4 );
$p5 = get_field( "wert", $s5 );
$p6 = get_field( "wert", $s6 );
$p7 = get_field( "wert", $s7 );
$p8 = get_field( "wert", $s8 );
$p9 = get_field( "wert", $s9 );
$p10 = get_field( "wert", $s10 );

$check = [$p1, $p2, $p3, $p4, $p5, $p6, $p7, $p8, $p9, $p10];


if (in_array(0, $check)) {
    echo "Got 0";
}else {
    echo "No 0";
} 

Having such an amount of variables is no good practice.拥有如此多的变量并不是一个好习惯。 You should use arrays for that.您应该为此使用 arrays 。

When you know how many fields need to be positive, you can just count them.当您知道有多少字段需要为正时,您就可以计算它们。

$values = [];
$max    = 10;
for ($i = 1; $i <= $max; $i++) {
    $values[] = get_field('wert', ${"s$i"});
}

$filled = array_reduce($values, fn($carry, $value) => $carry += (isset($value) && $value != 0) ? 1 : 0, 0);
if ($filled !== $max) {
    echo "Only $filled of $max are filled";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM