PDA

View Full Version : Terinary operator in PHP


Useless
2005-04-06, 10:40 PM
Fuck me with a stick.

I have this piece of code which pulls words from flatfile databases:

$sentence = ($type ?
"$word1[0] $word2[0] $word3[0] $word4[0]" :
"$word1[0] $word2[0] $word3[0] $word4[0] $word5[0]");

In it's present form, I can only produce two different layouts for word strings, aka sentences. I'd like to be able to offer more layouts, but I can't figure out how to add another line without getting an error. Damn it. It's that fucking colon.

cd34
2005-04-06, 11:00 PM
that statement means:


if ($type) {
$sentence = "$word1[0] $word2[0] $word3[0] $word4[0]";
} else {
$sentence = "$word1[0] $word2[0] $word3[0] $word4[0] $word5[0]";
}

Useless
2005-04-06, 11:56 PM
Neat, thanks. ;) A little more understandable for a guy like me. I swapped out the original code with yours and all worked well. Here is where I run into trouble though. I'd like to be able to add a third expression, but can't figure out how. My top secret script 'chooses' which sentence to to create from the two current expressions. Is it possible to add a third expression to that? It works fine as is, but could be made better in the future if I was able to add more junk.

cd34
2005-04-07, 12:23 AM
$type would need to have more than a true/false value.

you could do something like


switch ($type) {
case 0:
$sentence = "$word1[0] $word2[0] $word3[0] $word4[0]";
break;
case 1:
$sentence = "$word1[0] $word2[0] $word3[0] $word4[0] $word5[0]";
break;
case 2:
asdfhaskdhflasjdhflashdf
break;
default:
asdjhflasjhdfljashdflkjhasdf
break;
}


Then you just have to set $type to something other than 0/1 or false/true.

Useless
2005-04-07, 12:41 AM
Woohoo! It works! Thank you.
With $type = mt_rand(0,3); it works just as I had hoped.

You da man |thumb

cd34
2005-04-07, 12:43 AM
nah, just one of 3.1 billion.