如何在 PHP 中简单地压缩多个 IF 语句
How to condense multiple IF statements simply in PHP
这是我的代码。它可以工作并运行并完成我想让它做的所有事情,但它太长了。我怎样才能浓缩它?我的PHP水平是基础。
我会使用数组吗?还是一个功能?您能否 post 您可以用来提高效率的代码?
<?php
$product = $result[CategoryId];
if ($product == "1") {
echo "Tonneau Cover to suit";
} elseif ($product == "2") {
echo "Clip On Tonneau Cover to suit";
} elseif ($product == "3") {
echo "INSERT";
} elseif ($product == "4") {
echo "INSERT";
} elseif ($product == "5") {
echo "INSERT";
} elseif ($product == "6") {
echo "INSERT";
} elseif ($product == "7") {
echo "INSERT";
} elseif ($product == "8") {
echo "INSERT";
} elseif ($product == "9") {
echo "INSERT";
} elseif ($product == "10") {
echo "INSERT";
} elseif ($product == "11") {
echo "INSERT";
} elseif ($product == "12") {
echo "INSERT";
} elseif ($product == "13") {
echo "INSERT";
} elseif ($product == "14") {
echo "INSERT";
} elseif ($product == "15") {
echo "INSERT";
} elseif ($product == "16") {
echo "INSERT";
} elseif ($product == "17") {
echo "INSERT";
} else {
echo ".";
}
?>
根据示例中的内容:
<?php
$product = (int) $result['CategoryId'];
if ($product === 1) {
echo "Tonneau Cover to suit";
} elseif ($product === 2) {
echo "Clip On Tonneau Cover to suit";
} elseif ($product >=3 || $product <=17) {
echo "INSERT";
} else {
echo ".";
}
?>
是的,你可以用这种方式使用数组
$product = $result[CategoryId];
$ogh=["Tonneau Cover to suit","Clip On Tonneau Cover to suit","INSERT"];
if(count($ogh)>$product)
echo $ogh[$product];
else
echo "Invalid";
这是我的代码。它可以工作并运行并完成我想让它做的所有事情,但它太长了。我怎样才能浓缩它?我的PHP水平是基础。
我会使用数组吗?还是一个功能?您能否 post 您可以用来提高效率的代码?
<?php
$product = $result[CategoryId];
if ($product == "1") {
echo "Tonneau Cover to suit";
} elseif ($product == "2") {
echo "Clip On Tonneau Cover to suit";
} elseif ($product == "3") {
echo "INSERT";
} elseif ($product == "4") {
echo "INSERT";
} elseif ($product == "5") {
echo "INSERT";
} elseif ($product == "6") {
echo "INSERT";
} elseif ($product == "7") {
echo "INSERT";
} elseif ($product == "8") {
echo "INSERT";
} elseif ($product == "9") {
echo "INSERT";
} elseif ($product == "10") {
echo "INSERT";
} elseif ($product == "11") {
echo "INSERT";
} elseif ($product == "12") {
echo "INSERT";
} elseif ($product == "13") {
echo "INSERT";
} elseif ($product == "14") {
echo "INSERT";
} elseif ($product == "15") {
echo "INSERT";
} elseif ($product == "16") {
echo "INSERT";
} elseif ($product == "17") {
echo "INSERT";
} else {
echo ".";
}
?>
根据示例中的内容:
<?php
$product = (int) $result['CategoryId'];
if ($product === 1) {
echo "Tonneau Cover to suit";
} elseif ($product === 2) {
echo "Clip On Tonneau Cover to suit";
} elseif ($product >=3 || $product <=17) {
echo "INSERT";
} else {
echo ".";
}
?>
是的,你可以用这种方式使用数组
$product = $result[CategoryId];
$ogh=["Tonneau Cover to suit","Clip On Tonneau Cover to suit","INSERT"];
if(count($ogh)>$product)
echo $ogh[$product];
else
echo "Invalid";