doude2635 2013-04-12 09:51
浏览 66

php在echo语句中使用switch

I need to use a statement like switch within echo statement

I found a way for this ,but i think this is not the best way for this when we want to use IF inside echo,write some thing like:

echo ((condition)?'print this if condition is True':'print this if condition is False');

we could use this method for a way like switch:

echo ((case1)?'case 1 result':((case2)?'case2 result':((case3)?'case3 result':'default result')));

are you know a better way for this?

  • 写回答

2条回答 默认 最新

  • dongyongan9941 2013-04-12 09:54
    关注

    Your example is called ternary operators its basically short hand for an if statement.

    So in your second example you're just doing a load of chained if then else's

    You're far better off doing something like this

        switch ($type)) {
        case "txt":
             $output = "images/doctypes/icon_txt.gif";
        break;
        case "doc":
             $output = "images/doctypes/icon_doc.gif";
        break;
        case "docx":
             $output = "images/doctypes/icon_doc.gif";
        break;
        case "pdf":
             $output = "images/doctypes/icon_pdf.gif";
        break;
        case "xls":
             $output = "images/doctypes/icon_xls.gif";
        break;
        case "xlsx":
             $output = "images/doctypes/icon_xls.gif";
        break;
        case "ppt":
             $output = "images/doctypes/icon_ppt.gif";
        break;
        case "pptx":
             $output = "images/doctypes/icon_txt.gif";
        break;
        case "rtf":
             $output = "images/doctypes/icon_txt.gif";
        break;
        case "zip":
             $output = "images/doctypes/icon_zip.gif";
        break;
        case "rar":
             $output = "images/doctypes/icon_zip.gif";
        break;
        case "mdb":
             $output = "images/doctypes/mdb.gif";
        break;
        default:
             $output = "images/doctypes/icon_generic.gif";
        };
    
    echo $output;
    
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型