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!

4
  • 2
    Try removing & from the second attempt. Commented Dec 15, 2017 at 12:59
  • You could try array_diff. Commented Dec 15, 2017 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. Commented Dec 15, 2017 at 13:10
  • $positions = array_filter($positions, function($x) { return $x['date'] != '1'; }); Commented Dec 15, 2017 at 14:55

3 Answers 3

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]);
    }    
}
Sign up to request clarification or add additional context in comments.

Comments

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

I hope help you. :)

Comments

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.