Reputation:
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?
Upvotes: 1
Views: 36
Reputation: 2856
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!
Upvotes: 1
Reputation:
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;
Upvotes: 2