我有变量$var
,可以是"text1", "text2", "text3", "text4"
。我想为$varWord
中的每一个分配不同的$var
。这段代码适用于此,但它非常庞大,我如何优化它(使if / elseif更少)?
<?php
if ($var == "text1") {
$varWord = "word1";
} elseif ($var == "text2") {
$varWord = "word2";
} elseif ($var == "text3") {
$varWord = "word3";
} elseif ($var == "text4") {
$varWord = "word4";
}
?>
答案 0 :(得分:0)
感谢deceze。这是最终的工作代码:
$var = 'text1';
$words = array('text1' => 'word1', 'text2' => 'word2', 'text3' => 'word3', 'text4' => 'word4');
$varWord = $words[$var];
echo $varWord;