我真的需要在
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
}
.
我希望你能理解我的问题并能帮忙...谢谢...
就这么简单:
$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
}