0

I have various items in my $positions array and do the following:

foreach ($positions as &$position) {

    if ($position['date'] == $order['date']) {
        unset($position);
    }
}
var_dump($positions);

The var_dump still displays the $position which should be excluded.

When I do

foreach ($positions as $key => &$position) {
    if ($position['date'] == $order['date']) {
        unset($positions[$key]);
    }    
}

It does remove far more items than expected.

Anybody knows what happens here in both cases and how why does unset($position) not work? I reference the item in the foreach loop with '&'.

Thanks!

Torben
  • 5,388
  • 12
  • 46
  • 78
  • 2
    Try removing `&` from the second attempt. – FirstOne Dec 15 '17 at 12:59
  • You could try [array_diff](http://php.net/manual/en/function.array-diff.php). – FirstOne Dec 15 '17 at 12:59
  • I think I got it. It does remove more items than expected in the second case, because some values are stored like this "-0001-11-30 00:00:00.000000" in the database as the datetime, but I expected everything has a valid date or NULL. – Torben Dec 15 '17 at 13:10
  • `$positions = array_filter($positions, function($x) { return $x['date'] != '1'; });` – splash58 Dec 15 '17 at 14:55

3 Answers3

1

Instead of using &$variableName use $varibaleName, because there is not concept of pointers in php and not proper used of reference operator causes unexpected results sometimes.

foreach ($positions as $key => $eachPosition)
{
    if ($eachPosition['date'] == $order['date']) 
    {
        unset(positions[$key]);
    }    
}
splash58
  • 26,043
  • 3
  • 22
  • 34
Gaurav Kumar
  • 334
  • 1
  • 7
0

Assuming you want to delete the $position['date'] value; instead of using unset($positions[$key]) you could do the following :

foreach ($positions as $key => $position) {
    if ($position['date'] == $order['date']) {
        unset($position['date']);
    }    
}

NB : I removed the reference in the foreach loop because according to your example it's not used and can cause unexpected behaviours (PHP foreach by reference causes weird glitch when going through array of objects).

Nico
  • 439
  • 3
  • 16
0
foreach ($positions as $position) {
  ($position['date'] == $order['date']) ? unset($position['date']) : '';   
}

I hope help you. :)

Santo Boldizar
  • 1,255
  • 14
  • 17