sooraj s pillai
sooraj s pillai

Reputation: 916

Switch case for array combination

I've written a switch which needs to match any combinations in the predefined array but now its matching only if all the combination from the given array is succeeded. But I want to match any combination from the array.

example : if my combination consists only 'man','cisman' then also my combination needs to succeed and needs to return $result = "male.png";. But if any item otherthan the given combination needs to rejected and needs to return default case.

Working demo

$menCombo = ['man','cisman','transmasculine','transman'];
$womanCombo = ['woman','ciswoman','transfeminine','transwoman'];

            switch($genderdetail) {
                case count(array_intersect($menCombo, $genderdetail)) === count(($menCombo)):
                case "man":
                case "cisman":
                case "transman":
                case "transmasculine":{
                    $result = "male.png";
                    break;
                }
                case count(array_intersect($womanCombo, $genderdetail)) === count(($womanCombo)):
                case "woman":
                case "ciswoman":
                case "transfeminine":
                case "transwoman":{
                    $result = "female.png";
                    break;
                }
                default: {
                    $result = "others.png";
                    break;
                }
            }

Upvotes: 1

Views: 95

Answers (2)

nice_dev
nice_dev

Reputation: 17805

As mentioned in the comments, if $genderdetail isn't an array, you make it one. Now, if array difference of 2 arrays returns empty, it sure has to belong to the haystack array in comparison.

<?php

$genderdetail = ['man','cisman'];
$menCombo = ['man','cisman','transmasculine','transman'];
$womanCombo = ['woman','ciswoman','transfeminine','transwoman'];

$result = 'others.png';

if(!is_array($genderdetail)){
    $genderdetail = [ $genderdetail ];
}

if(empty(array_diff($genderdetail, $menCombo))){
    $result = 'male.png';
}else if(empty(array_diff($genderdetail, $womanCombo))){
    $result = 'female.png';
}

echo $result;

Upvotes: 2

Gergo
Gergo

Reputation: 125

What about changing the count condition to

case count(array_intersect($menCombo, $genderdetail)) === count(($genderdetail)):

you count the array mayches and not the long array of poszibilities. Same for the female count.

Upvotes: 0

Related Questions