php array remove n amount of items based on value

I have this array, there are 4 values = 3, how can i delete just two of them?

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

I already tried unset(). is there any way to achieve this ?

so the array looks like this

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

Upvotes: 0

Views: 69

Answers (2)

The fourth bird
The fourth bird

Reputation: 163467

You might use a loop and skip the first 2 times you encounter a 3. Then for the next matches, you could use unset. Then you might use array_values to reset the keys:

$items = [
    1,2,1,2,3,3,3,2,2,2,1,2,3,2
];

$found  = 0;
foreach ($items as $key => $item) {
    if ($item === 3) {
        if ($found < 2) {
            $found++;
            continue;
        }
        unset($items[$key]);
    }
}
print_r(array_values($items));

Result

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

Php demo

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522161

Just make two calls to unset, using array_search:

$array = array(1,2,3,3,3,4,5,6);
print_r($array);
unset($array[array_search(3, $array)]);
unset($array[array_search(3, $array)]);
print_r($array);

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 3
    [4] => 3
    [5] => 4
    [6] => 5
    [7] => 6
)

Array
(
    [0] => 1
    [1] => 2
    [4] => 3
    [5] => 4
    [6] => 5
    [7] => 6
)

But this assumes that you are OK with the behavior of array_search, which would return the first index which matches the value 3. If you had some other order of removal in mind, then state it, and the code might have to be changed.

Upvotes: 2

Related Questions