Torben
Torben

Reputation: 5494

PHP - array unset not working in foreach loop

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!

Upvotes: 0

Views: 287

Answers (3)

Nico
Nico

Reputation: 459

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

Upvotes: 0

Gaurav Kumar
Gaurav Kumar

Reputation: 336

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]);
    }    
}

Upvotes: 1

Santo Boldizar
Santo Boldizar

Reputation: 1395

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

I hope help you. :)

Upvotes: 0

Related Questions