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?

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;

Hmm. If I understand correctly, you want to know the how-maniest condition was the first successful one?

I just thought this up... See if it fits you.

Just replace the false/true with your conditions.

$i = 0;
++$i AND false OR // 1
++$i AND false OR // 2
++$i AND false OR // 3
++$i AND true  OR // 4 (here we go)
++$i AND false OR // 5
++$i AND true  OR // 6 (ignored)
++$i AND false OR // 7
$i = 0;           // 0

echo "case" . $i . " result"; // echoes 'case4 result' 

EDIT:
Here is another approach with the same technique.
But in stead of a counter, you can give your own on-success string.
Remember to just replace the false/true with your conditions.

function dostuff($str) { echo $str; return true;}

false AND dostuff('string1') OR
false AND dostuff('string2') OR
false AND dostuff('string3') OR
true  AND dostuff('string4') OR // echoes 'string4'
false AND dostuff('string5') OR
true  AND dostuff('string6') OR // ignored
false AND dostuff('string7');