duanhuang4306 2014-11-07 18:36
浏览 17
已采纳

如何使这个PHP if语句更简单,更短?

I have feeling that the following code can be shortened but have no idea how to rewrite it :)

$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';

if( $post_type == 'faq' && !isset( $_REQUEST['mode'] ) )
  $_REQUEST['mode'] = 'excerpt';

// if I just go with else... it doesn't work
elseif( $post_type !== 'faq' && !isset( $_REQUEST['mode'] ) )
  $_REQUEST['mode'] = 'list';

Update

As you can see, !isset( $_REQUEST['mode'] ) is used twice. $post_type == 'faq' is also used twice, but in the elseif I'm checking negative.

Seriously there is no way to rewrite it to one if without else...?

  • 写回答

7条回答 默认 最新

  • dquh37673 2014-11-07 18:56
    关注

    How about using a ternary operator for testing 'faq' ?

    $post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
    if (!isset( $_REQUEST['mode'] )) {
        $_REQUEST['mode'] = ($post_type == 'faq') ? 'excerpt' : 'list';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)