douluan1533 2015-11-02 03: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 03: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部