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条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?