php8 - 在匹配表达式中使用关联数组

问题描述 投票:0回答:1

我真的需要在

associative array
表达式中使用
match
。因为,我可以将
associative array
用于其他目的..

示例(我所期望的):

$rank = [
    '1' => 'Beginner',
    '2' => 'Intermediate',
    '3' => 'Expert',
    '4' => 'Super Pro',
];

match ($user->rank) {
    ($rank), // This is what I expected, but it is not working
    default => 'N/A',
};

// why I want to be able to use associative array?
// because I can use the `$rank` variable for another purpose
// example

foreach ($rank as $each_rank) {
    // bla bla bla
}

。 .

目前我所做的是:

match ($user->rank) {
    '1' => 'Beginner',
    '2' => 'Intermediate',
    '3' => 'Expert',
    '4' => 'Super Pro',
    default => 'N/A',
};

// so now, this is quite anoyying
// because now, I need to write same code TWICE
// now, for another purpose, I need to write once again the same data

$rank = [
    '1' => 'Beginner',
    '2' => 'Intermediate',
    '3' => 'Expert',
    '4' => 'Super Pro',
];

foreach ($rank as $each_rank) {
    // bla bla bla
}

.

我希望你能理解我的问题并能帮忙...谢谢...

match php-8
1个回答
0
投票

就这么简单:

$rank = [
    '1' => 'Beginner',
    '2' => 'Intermediate',
    '3' => 'Expert',
    '4' => 'Super Pro',
];

$rk='5';

$expressionResult = match (true) {
    in_array($rk, array_keys($rank)) === true => $rank[$rk], // This is what I expected, but it is not working
    default => 'N/A',
};

echo $expressionResult;

// why I want to be able to use associative array?
// because I can use the `$rank` variable for another purpose
// example

foreach ($rank as $each_rank) {
    // bla bla bla
}
© www.soinside.com 2019 - 2024. All rights reserved.