0

I can not understand. Why this code remove last item. But if i change $item in second loop on $item2, or use link, it work fine.

<?php
$list = [
    ['id' => 1],
    ['id' => 2],
    ['id' => 3],
    ['id' => 4],
    ['id' => 5],
    ['id' => 6],
];

$selected = [2,3,4,6];
$hidden = [4,5];

foreach ($list as &$item) {
    if(in_array($item['id'], $selected)) {
        $item['selected'] = true;
    }
}

foreach ($list as $key=>$item) {
    if(in_array($item['id'], $hidden)) {
        unset($list[$key]);
    }
}

var_dump($list);
2
  • 1
    use unset($item) after the first foreach to break the association of $item with the last array element Commented Mar 14, 2017 at 15:21
  • why, in first foreach you are accessinng to &$item ... ??? Commented Mar 14, 2017 at 15:22

2 Answers 2

2

as the documentation states:

Warning: Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

so something like this should work:

foreach ($list as &$item) {
    //do some stuff
}
unset($item);
Sign up to request clarification or add additional context in comments.

Comments

0

unset() the hidded keys first and then check for selected id's

foreach ($list as $key => $item) {
    if(in_array($item['id'],$hidden)){
        unset($list[$key]);
    } 
}

foreach ($list as &$item) {
    if(in_array($item['id'], $selected)) {
        $item['selected'] = true;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.