Home > Blockchain >  Check multiple variables if set and not 0
Check multiple variables if set and not 0

Time:08-27

I have multiple variables and i need to check if all of these variables are set or not "0". So all of these variables need to have a value.

The values i get from 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($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". How can i check this as short as possible?

Thank you so much!

CodePudding user response:

Your check is checking the $s variables and this is not the value of the fields, which are stored in $p variables.

CodePudding user response:

You can convert variables to array, and check with 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";
} 

CodePudding user response:

Having such an amount of variables is no good practice. You should use arrays for that.

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";
}
  • Related