-1

I'm trying to unset() some elements from an array but when using a foreach loop to go through 1 array to delete these elements from another array it does not seems to be working.

    if (isset($this->request->post['merge'])) {
        $merge_orders = $this->request->post['merge'];  
    }       

    $selected_order = min($merge_orders); // Fetch the max value order_id 

    unset($merge_orders[$selected_order]); // Take it out of the array. 

    $orders_list = explode(',', $this->request->post['order_id_list']);

    $removeKeys = $merge_orders;

    foreach($removeKeys as $key) {
       unset($orders_list[$key]);
       echo $key;
    }

    echo print_r($orders_list);

The first unset works fine but the second does not, the array is set and properly formatted but it still does not seem to remove the elements from the $orders_list array.

user3285356
  • 67
  • 1
  • 9
  • You're not looping through `$orders_list`.... – Kisaragi Aug 18 '15 at 18:50
  • That's because it's the elements that are left in the $merge_orders array that I wish to remove – user3285356 Aug 18 '15 at 18:55
  • @Kisaragi If you try and process the array you are trying to unset occurances in the foreach loop gets lost and confused. OP is using the right idea but see my answer for the reason the unset's are not working – RiggsFolly Aug 18 '15 at 18:57

1 Answers1

1

If you only use one parameter on a foreach loop you are delivered the value of the occurance and not the key for the occurance.

Try this so that you are getting a key from the foreach loop and not a value

foreach($removeKeys as $key => $val) {
   unset($orders_list[$key]);
   echo $key;
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149