phparrays

How to check if an associative array contains a value and only that value?


I need to check if an associative array contains a certain value and only that value. So for example key choice needs to contain the value Afhalen.

Below an example array:

Array
(
    [Test product1644] => Array
        (
            [artikelid] => 644
            [product] => Test product
            [price] => 20,00
            [picture] => images/_bad_noimg.jpg
            [quantity] => 1
            [alias] => test-product-2
            [catalias] => stormbanen-huren
            [prodoptie] => 1644
            [choice] => Bezorgen
        )

    [Test product2644] => Array
        (
            [artikelid] => 644
            [product] => Test product
            [price] => 90,00
            [picture] => images/_bad_noimg.jpg
            [quantity] => 1
            [alias] => test-product-2
            [catalias] => stormbanen-huren
            [prodoptie] => 2644
            [choice] => Bezorgen & Opbouw
        )

    [Test product3644] => Array
        (
            [artikelid] => 644
            [product] => Test product
            [price] => 100,00
            [picture] => images/_bad_noimg.jpg
            [quantity] => 1
            [alias] => test-product-2
            [catalias] => stormbanen-huren
            [prodoptie] => 3644
            [choice] => Bezorgen & Afhalen
        )

    [Test product4644] => Array
        (
            [artikelid] => 644
            [product] => Test product
            [price] => 200,00
            [picture] => images/_bad_noimg.jpg
            [quantity] => 1
            [alias] => test-product-2
            [catalias] => stormbanen-huren
            [prodoptie] => 4644
            [choice] => Afhalen
        )

)

Above array should return false since there are more choice keys with values other than Afhalen.

Below array should return true since choice always contains Afhalen:

Array
(
    [Test product4644] => Array
        (
            [artikelid] => 644
            [product] => Test product
            [price] => 200,00
            [picture] => images/_bad_noimg.jpg
            [quantity] => 1
            [alias] => test-product-2
            [catalias] => stormbanen-huren
            [prodoptie] => 4644
            [choice] => Afhalen
        )

    [Test product4646] => Array
        (
            [artikelid] => 649
            [product] => Test product
            [price] => 200,00
            [picture] => images/_bad_noimg.jpg
            [quantity] => 1
            [alias] => test-product-2
            [catalias] => stormbanen-huren
            [prodoptie] => 4644
            [choice] => Afhalen
        )
)

I've found a question on how to do this using javascript but nothing on how to do it using PHP.


Solution

  • $hasOnlySingleChoice = true;
    foreach ($array as $item) {
        if ($item['choice'] !== 'Afhalen') {
            $hasOnlySingleChoice = false;
            break;
        }
    }