-2

I have two arrays.

I have a foreach loop which is iterating through one of these arrays ($items). For each value in this array, if a condition is not true, I would like to unset that same key, but from another, similar array ($list). (The two arrays are not identical, but the key will always be the same).

I am unsure how to go about this. The code I used below did not successfully unset the record from the first array.

Both arrays do have keys (IDs), with secondary data.

$list = array(
    'id' => '2',
    'id' => '3',
    'id' => '4',
    'id' => '5',
    'id' => '6'
);

$items = array(
    'id' => '2',
    'id' => '3',
    'id' => '4',
    'id' => '5',
    'id' => '6'
);

foreach ($items AS $key => $item)
{
    if ($item['id'] != $setting)
    {
        unset($list[$key]);
    }
}
ButtressCoral
  • 113
  • 2
  • 13
  • Where are you getting `$item['id']` and `$setting` from? Is that double `= =` a typo in your post? Everything else looks fine. – bloodyKnuckles Jun 25 '14 at 18:40
  • I shall check this again, thanks. `$item['id']` refers to the (now updated) key entry of the `$items` array. `$setting` is just a variable as part of my project. – ButtressCoral Jun 25 '14 at 18:45
  • 3
    This is an array that cannot possibly exist, all keys in an array must be unique – Mark Baker Jun 25 '14 at 18:46

2 Answers2

2

What exactly are the keys in the arrays? Because, you cannot have every key in an array be the same. They overwrite each other. (Not sure if this is just for your example or not).

Anyway, using this code works, with tests to verify...

   <?php
$list = array(
    2,3,4,5,6
);
$items = array(
    2,3,4,5,6
);
$set = 3;
foreach($list as $key => $val){
    echo $key . " " . $val . "\n";
}
echo "\n -------------------- \n";
foreach($list as $key => $val){
    if ($list[$key] != $set){
        unset($items[$key]);
    }
}
foreach($items as $key => $val){
    echo $key . " " . $val . "\n";
}
?>

So, the actual working code to do what you are attempting to do is this:

$list = array(
    2,3,4,5,6
);
$items= array(
    2,3,4,5,6
);
$set = 3; //random variable to mock your $setting variable

foreach($list as $key => $val){
    if ($list[$key] != $set){
        unset($items[$key]);
    }
}
mtbjay
  • 76
  • 4
1

This loops through $items and for every value that does not equal $setting, remove from list.

$setting = 3;
$list = array('2','3','4','5','6');
$items = array('2','3','4','5','6');

foreach ($items AS $key => $item)
{
    if ($item != $setting)
    {
        unset($list[$key]);
    }
}

print_r($list);

Output:

Array ( [1] => 3 )

So $list now only contains the value 3.

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37