user3350731
user3350731

Reputation: 972

unset an array with a specfic condition

Basically I have this array $code:

Array
(
    [1] => Array
        (
            [0] => FRANCE
            [1] => 26422
            [2] => 61748
            [3] => 698477678
        )

    [2] => Array
        (
            [0] => UNITED STATES
            [1] => 545
            [2] => 2648
            [3] => 55697455
        )

    [3] => Array
        (
            [0] => CANADA
            [1] => 502
            [2] => 1636
            [3] => 15100396
        )
    [4] => Array
        (
            [0] => GREECE
            [1] => 0
            [2] => 45
            [3] => 458
        )

I want to unset all the countries with $code[$key][1] == 0 so I tired this:

$code = array_filter($code, function (array $element) {
return !preg_match('(0)i', $element[1]);
});

But it returns all the countries unless the one that has in $code[$key][1] 0, Like this:

Array
(
    [1] => Array
        (
            [0] => FRANCE
            [1] => 26422
            [2] => 61748
            [3] => 698477678
        )

    [2] => Array
        (
            [0] => UNITED STATES
            [1] => 545
            [2] => 2648
            [3] => 55697455
        )

Any how I can achieve this? Thanks!

Upvotes: 0

Views: 51

Answers (2)

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

Without regex:

$code = array_filter($code, function (array $element) {
return ($element[1] !== 0);
});

With regex (you need to use anchors):

$code = array_filter($code, function (array $element) {
return !preg_match('/^0$/', $element[1]);
});

However, I’ll recommend a simple foreach loop instead of array_filter:

foreach($code as $key => $val){
    if($val[1] === 0) unset($code[$key]);
}

Upvotes: 2

user3528035
user3528035

Reputation: 21

If I understand, you are trying to remove only Greece, it should be as simple as:

$code = array_filter($code, function (array $element) {
    return $element[1] != 0
});

The regular expression you are using will remove every country where the key has a 0 in the value, that will exclude also 502 in your example.

Upvotes: 1

Related Questions