douluan1533 2015-11-02 11:05
浏览 279
已采纳

如何将if if语句转换为三元运算符?

I have a piece of code and I want to convert it to ternary operator. Can anyone help? It has 1 if and 2 else if conditions so I am having trouble converting it. Here is my code.

if ($this->session->data['desired_service']==1){
    echo 'Home Delivery';
} else if ($this->session->data['desired_service']==2){
    echo 'Take Away';
} else if ($this->session->data['desired_service']==3){
    echo 'DinIN';
}

Here is the code that I have used so far.

$service = ( $this->session->data['desired_service']== 1 ) ? "Home Delivery" : ( $this->session->data['desired_service'] == 2 ) ? "Take Away" : ( $this->session->data['desired_service'] == 3 ) ? "DinIN";

But it is giving me a syntax error.

  • 写回答

2条回答 默认 最新

  • dqch34769 2015-11-02 11:08
    关注
    echo ($this->session->data['desired_service'] == 3) ? 'DinIN' : (($this->session->data['desired_service']==1) ? 'Home Delivery' : ($this->session->data['desired_service'] == 2) ? 'Take Away' : '');
    

    Explanation:

    Use nested ternary operator.

    If variable equal to 3, print 'DinIN'    
    else : two cases:
    if 1 : Home Delivery
    else : Take Away
    

    Demos:

    if value is 1

    If value is 2

    if value is 3

    Another solution

    Use predefined array:

    Get all your options in an array and add

    1,2 and 3 as keys.

    Check array with isset and the variable.

    If it is set, print it, else blank.

    Purpose solved.

    <?php
    $arr = array();
    $arr[1] = 'Home Delivery';
    $arr[2] = 'Take Away';
    $arr[3] = 'DinIN';
    echo isset($arr[$this->session->data['desired_service']]) ? $arr[$this->session->data['desired_service']] : '';
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度