5

I'm using this function to check if certain products are in the cart on my woocommerce. This works on my localhost but is giving me a:

Can't use function return value in write context

on server.

function product_is_in_the_cart() {
$ids = array( '139, 358, 359, 360' );

$cart_ids = array();

// Find each product in the cart and add it to the $cart_ids array
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
    $cart_product = $values['data'];
    $cart_ids[]   = $cart_product->id;
}

// Si uno de los productos introducidos en el array esta, devuelve false
if ( ! empty( array_intersect( $ids, $cart_ids ) ) ) {
    return true;
} else {
    return false;
}} 

I'm trying to find other methods to do this but i cant find a answer to my problem, I think is because of empty() but how can i do this on other way?

Gouda Elalfy
  • 6,888
  • 1
  • 26
  • 38
MidouCloud
  • 403
  • 1
  • 7
  • 20

3 Answers3

4

I see this is tagged php 5.3

In versions of php before 5.5 empty() will only accept a variable. You will need to assign it first like so:

$isEmpty = array_intersect($ids, $cart_ids);

if ( !empty($isEmpty) ) {
...
}
danjam
  • 1,064
  • 9
  • 13
  • Then your intersection between `$ids` and `$cart_ids` is not empty, you need to look at that next. – danjam Dec 23 '15 at 11:13
1

Upgrade your server's PHP.

Check the PHP version on your machine and the server. as mentioned in the documentation, in older version you could only pass the variable.

Prior to PHP 5.5, empty() only supports variables;

Ali
  • 2,993
  • 3
  • 19
  • 42
  • I already know that, thats why i was asking for an alternative method. – MidouCloud Dec 23 '15 at 10:44
  • 2
    Ideally you should upgrade your PHP version, if it's not possible go with charging a variable with the result of your method – Ali Dec 23 '15 at 10:49
0

The function is now working like this:

function product_is_in_the_cart() {
global $woocommerce;
$items = array( '139, 240, 242, 358, 359, 360' );
// Create array from current cart
$cartitems = $woocommerce->cart->get_cart();
// Count items in cart
$itemcount = count( $cartitems );
        foreach($cartitems as $cartitem) {
            $productid = $cartitem[product_id];
            if(in_array($productid,$items)) {
                return true;
            } else 
            { 
                return false;
            }
        }
}
MidouCloud
  • 403
  • 1
  • 7
  • 20