Madelyn Cruz Madelyn Cruz - 2 months ago 6
PHP Question

Check if and only if array contains a specific object

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;

Answer

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