为每个$ var分配$ varText(优化if / elseif代码)

时间:2015-04-13 07:11:32

标签: php variables if-statement optimization

我有变量$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";
}
?>

1 个答案:

答案 0 :(得分:0)

感谢deceze。这是最终的工作代码:

$var = 'text1'; 
$words = array('text1' => 'word1', 'text2' => 'word2', 'text3' => 'word3', 'text4' => 'word4'); 
$varWord = $words[$var];
echo $varWord;