阵列组合开关盒

Switch case for array combination

我写了一个开关,它需要匹配预定义数组中的任何组合,但现在它只有在给定数组的所有组合都成功时才会匹配。但我想匹配数组中的任意组合。

示例:如果我的组合仅包含 'man','cisman',那么我的组合也需要成功并且需要 return $result = "male.png";。但是如果除了给定组合之外的任何项目需要拒绝并且需要 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;
                }
            }

把计数条件改成

怎么样

案例计数(array_intersect($menCombo, $genderdetail)) === 计数(($genderdetail)):

你计算的是数组的混乱,而不是一长串的可能性。女性人数也一样。

如评论中所述,如果 $genderdetail 不是数组,则将其设为一个。现在,如果2个数组的array difference returns为空,那么比较起来肯定属于haystack数组。

<?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;