Search code examples
phparrayswoocommerceordersunset

Remove item from array if value equals


On the Woocommerce order page, I have of items in the order, through which I want to loop and exclude a specific item by product id.

$order->get_order_number();
$items = $order->get_items();

foreach( $items as $key => $value) :
     $exclude = $value->get_product_id();
     if( in_array($exclude, array('3404') ) {  
        unset($items[$key]);
     }
  }
endforeach;

$new_items = array_values($items);

I thought this would loop through the original array, remove the $item whose $product_id == 3404 and then reindex.

I'm having no luck here. Any thoughts?

Solved ->

        //Filter out colon cleanse duo
    $items = array_filter($order->get_items(), function($item) {
        return $item->get_product_id() != 3404;
    });

    //Randomize ids and grab one
    shuffle($items);
    foreach( $items as $item) :

        $product_id = $item->get_product_id();
        $product_name = $item->get_name();

        break;
    endforeach;

Solution

  • You should be able to do this:

    $items = array_filter($order->get_items(), function($item) {
        return $item->get_product_id() != 3404;
    });
    

    This iterates over $items and passes like a foreach each value to $item. If the callback of array_filter returns a true, the value will be kept else dropped.

    You even can pass $order->get_items() directly in without fetching the items to an array.

    Additionally if you require to exclude more than one, as asked in your comment, you can do like so:

    $items = array_filter($order->get_items(), function($item) {
        return !in_array($item->get_product_id(), [3404, 6890]);
    });