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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀