我目前使用這一個導航列表,突出活動頁面:什麼是最簡潔的方式來檢查變量是否與PHP中的某個值範圍匹配?
<?= ($current_page == 'thema_list' ? 'class="on"' : '') ?>
擴展這一檢查另一頁是:
<?= ($current_page == 'thema_list' || $current_page == 'thema_edit' ? 'class="on"' : '') ?>
是否有辦法避免這種重複?
我目前使用這一個導航列表,突出活動頁面:什麼是最簡潔的方式來檢查變量是否與PHP中的某個值範圍匹配?
<?= ($current_page == 'thema_list' ? 'class="on"' : '') ?>
擴展這一檢查另一頁是:
<?= ($current_page == 'thema_list' || $current_page == 'thema_edit' ? 'class="on"' : '') ?>
是否有辦法避免這種重複?
爲2倍的值,這可能是對所花費的時間PHP來處理它的量最快的方法,但是如果你有很多的值,你可以使用in_array:
<?= (in_array($current_page, array('thema_list', 'thema_edit')) ? 'class="on"' : '') ?>
還檢查了this question關於與in_array相關的一些速度測試,而不是單獨檢查每個值。
你可以使用一個數組in_array()
$matches = array("thema_list", "thema_edit", "thema_other");
if (in_array($current_page, $matches)) {
echo 'class="on"'
}
你可以把它們放入數組,然後使用:
if(in_array($current_page, $array_values))
{
echo 'class on';
}