0

I need to set $use_paypal to TRUE only if the $products array contains one or more objects with term_id property set to 36.

This code works if $products contains one or more 36-items, but it also sets $use_paypal to TRUE if $products contains other items.

$use_paypal = FALSE;
foreach ($products as $product) {
  // The values could be 30, 31, 32, 33, 34, 35, 36
  if ($product->term_id == 36) {
    $use_paypal = TRUE;
  }
}
return $use_paypal;
6
  • 1
    what is your problem here? Commented Sep 12, 2016 at 6:27
  • I only need to use PayPal if the item in your cart are all apparel. If you have accessories, apparel etc. then, it should return false, Commented Sep 12, 2016 at 6:32
  • add a bit of more code on your work to help you. Commented Sep 12, 2016 at 6:33
  • 1
    How the items in the cart looks like? is it an array? Commented Sep 12, 2016 at 6:35
  • Can you provide us with your product class? Commented Sep 12, 2016 at 6:36

2 Answers 2

3

To make sure all of your products have apparel_id = 36 what I would do is set $use_paypal to true by default and if any of the products do not match, switch it to false. Take a look at this example:

foreach ($products as $product) {
    if ($product->term_id != 36) {
        return false;
    }
}
return true;

To make you understand what happens.

  • We set $use_paypal to true
  • We loop through all products
  • For each product we check if $product->term_id is not 36
  • If the term_id is not 36 we set $use_paypal to false
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. I'll try this one. Just a bit confused, what if the items in cart has values like this 30, 31, 36? Will it return to true?
No it will not. It will only return true if they are all 36
Well, your explanation above really makes sense. Thank you so much for your help :)
You could improve the efficiency of this function by simply returning false inside the loop - there's no need to continue checking items once we know there is a mismatch
0

Assuming you cart items list is an array, like this,

$cart_items[] = $product (object);
$cart_items[] = $product (object);

you can use a function like below to do your work.

function isPaypal($cart_items){
    foreach( $cart_items as $product ){
        if ( $product->term_id != 36 ){
            return FALSE;
        }
    }
    return TRUE;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.