简体   繁体   中英

two foreach loop on if statement

Wondering if it's possible to have a foreach loop call on if statement like this :

if (class_exists('WooCommerce')) { 
    foreach (array_combine($val1, $val2) as $key => $row_values)
}
else {
    foreach ( $val1 as $key => $row_values ) 
}

{ begin of loop code

What I'm trying to do is to have a foreach loop if woocommerce plugin is active and to have another foreach loop if woocommerce isn't active.

This is not possible the way you try it, since that is invalid syntax.

What you can do is something like that:

<?php
$iterationArray = class_exists('WooCommerce') ? array_combine($val1, $val2) : $val1;
foreach ($iterationArray as $key => $row_values) {
    // begin of loop code
} // end loop

What you need to do if a condition before the loop to assign the variables you will use to loop, just like this:

if ( class_exists( 'WooCommerce' ) ) {
    $newVal = array_combine($val1, $val2);
} else {
    $newVal = $val1;
}

foreach ( $newVal as $key => $row_values ) {
    // do stuff
}

The result will be the same as what you were trying to do. But the syntax you proposed in your question is not supported in PHP, and can be worked around with the way proposed above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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