change original array values inside foreach php

313 Views Asked by At

I want to update an array inside foreach I tried this two code :

code 1 :

 foreach ($listOrders as $k => $order) {

    foreach ($listOrders as $key => $o) 
    {
      if ($o["id_order"] == $order["id_order"])
      {
         unset($listOrders[$key]);
      }
    }

in this codeunset is not working

code 2 :

     foreach ($listOrders as $k => &$order) {

     foreach ($listOrders as $key => $o) 
     {
        if ($o["id_order"] == $order["id_order"])
        {
           unset($listOrders[$key]);
        }
     }

If I use & with $order $listOrders will not returned all data that I want.

2

There are 2 best solutions below

0
On

Your error should be here

  foreach ($listOrders as $k => &$order) { 
                                ^

Remove &

Also you are iterating through your $listOrders twice with your code, won't your array list always be empty after the iteration is finished?

1
On

If you are simply trying to get a list of the orders in the list, you can use array_column() to index the list by id_order. As you can only ever have 1 entry in an array with a particular key, this will end up with the last entry with a particular order id in the array...

$uniqueList = array_column(listOrders, null, "id_order");

If you just need the list without the index, you can use array_values() to re-index the list.

$uniqueList = array_values(array_column(listOrders, null, "id_order"));