I'm trying to use PHP to identify the variable $category, and echo its Chinese name into the value of an input text area.
<input type="text" value="<?php ...code...?>"/>
If I use the Ternary Operator, it looks as crazy as the If-Else statement... The $category variable duplicates many times.
echo (($category == "vegetable") ? "蔬菜" :
(($category == "fruit") ? "水果" :
(($category == "meat") ? "肉類" :
(($category == "seafood") ? "海鮮" :
(($category == "junkFood") ? "零食" : "")))));
However, if I use the Switch statement, it makes my code so long...
switch ($category){
case "vegetable":
echo "蔬菜";
break;
case "fruit":
echo "水果";
break;
case "meat":
echo "肉類";
break;
case "seafood":
echo "海鮮";
break;
case "junkFood":
echo "零食";
}
Is there any other ternary operator for switch statement so as to make my code cleaner ?
Or is there any better way to modify my code ?
You can use a simple associative array :
$your_food = ["vegetable"=>"蔬菜", "fruit"=>"水果","meat"=>"肉類"...];
echo $your_food[$category];