0

I'm trying to search through array and unset some elements if they are present in other array.

[scores] => Array
    (
        [1100190] => 0.15783204288267
        [1100213] => 0.15893037336024
        [2100230] => 0.16258444005331
        [1100516] => 0.16554697418536
        [1100973] => 0.16967437235894
    )

[explanation codes] => Array
    (
        [1100190] => 0
        [1100213] => 0
        [2100230] => 0
        [1100516] => 0
        [1100973] => 0
    )

So, I want for example key "[1100190]" to be removed. This is what I have for now:

// filter out keys we don't want
for($j=0; $j < count($filterData); $j++) {
    $position = array_search($filterData[$j], $recs);
    if($position != false) {
        foreach($recs as $key => $arr) {
            unset($recs[$key][$position]);
        }
    }
 }

In $filterData I have for example: 11111, 1100190. I'm not getting anything for $position when I try to echo it and my filter is not working. Thanks in advance.

Solution:

foreach($recs as $key => $arr) {
    $position = array_search($key, $filterData);
    if($position != false) {
        unset($recs[$key]);
    }
}

This is what did the trick, thanks for help, especially keune.

2
  • You can search the key with: php.net/manual/en/function.array-key-exists.php Commented Aug 31, 2013 at 10:34
  • is $recs an array containing scores and explanation codes? Commented Aug 31, 2013 at 10:34

2 Answers 2

1

As suggested I would use array key exists

foreach ($filterData as $k => $v)
{
    if (array_key_exists($k, $recs))
    {
        unset($recs[$k]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to do the search in every key of the $recs array. Try this:

for($j=0; $j < count($filterData); $j++) {
    foreach($recs as $key => $arr) {
        $position = array_search($filterData[$j], $arr);
        if($position !== false) {
            unset($recs[$key][$position]);
        }
    }
}

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.