1

I have the array $allowedViewLevels with the following example elements:

Array (
    [0] => 1
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
) 

I want to loop trough this array and check if the values are equal to 1, 8 or 11. If so, the corresponding elements should be deleted from the array.

For that, I used the following script:

foreach ($allowedViewLevels as $key) {
    if($key==1 || $key==8 || $key==11){
        unset($allowedViewLevels[$key]);
    } 
};

$niveis=implode(",", $allowedViewLevels);
print $niveis;  

Which is returning:

1,2,3,4,6,7,8,10,11 

So the elements in the array containing the values 1, 8 or 11 are not being unset from it. What can be wrong with this script?

1
  • You say you want to test the values, but the code tests the keys. Which do you really want to test? Commented Aug 24, 2013 at 13:58

2 Answers 2

2

I found the answer myself (with the help of this post)

It works with the following:

$allowedViewLevels=array_diff($allowedViewLevels, array(1,8,11));
$niveis=implode(",", $allowedViewLevels);
print $niveis; 
Sign up to request clarification or add additional context in comments.

Comments

1

An array contains pairs of [key] => value.

In your foreach loop, you should refer to it that way:

foreach ($allowedViewLevels as $key=>$value) {
    if ($value == 1 || $value == 8 || $value == 11) {
        unset($allowedViewLevels[$key]);
    }
} // Also: no semicolon here...

$niveis = implode(",", $allowedViewLevels);
echo $niveis;

But, as you've already found the answer yourself, kudos!

Comments

Your Answer

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