PDA

View Full Version : ternary statement?


Jason
02-13-2003, 12:04 AM
I learned a ternary statement but I would like to know more about them. Like say
if (condition){
blah1;
}
else {
blah2;
}
(condition)?blah1:blah2;

what if I wanted a nested if or something? or maybe a loop? how can I do this?


Jason

brothercake
02-13-2003, 01:18 AM
(condition)?true:(condition2)?true:(condition3)?true:false;

As far as I know you can go as deep as you like.

whammy
02-13-2003, 02:50 AM
You might want to parenthesize the other conditions to make it more readable, though...

BrainJar
02-13-2003, 04:15 AM
You can use code like this:


if (condition1) {
// first case
}
else if (condition2) {
// second case
}
else if (condition3) {
// third case
}
...
else {
// when all else fails
}


which is really just nesting if statements.

But sometimes it makes more sense to use a switch statement. Such as when you're simply testing the value of a single variable:


switch (x) {
case "A"
// first case
break;
case "B"
// second case
break;
...
default
// when all else fails
break;
}

ez4me2c3d
02-13-2003, 01:02 PM
he was talking ternary though...
you can asign values like thisx = (x==10) ? 0 : x+1;
this gives x a value depending on if x has a value of 10 or not. If not then it increments by 1, but if it is then it is reset to 0.

Ökii
02-13-2003, 01:15 PM
on an aside: as far as I've noted, php doesn't support multiple ternary operators in the same manner and would use syntax like

(a < 4) ? (a < 3) ? (a < 2) ? 1 : 2 : 3 : 4+;

just checked and javascript supports the same syntax.

note though: using == as a test tends to give the wrong result as it seems every test is done whether one has yielded a 'true' or 'false' return

to give an idea
<script>
a = Math.round(Math.random()*5);
b = (a == 4) ? (a == 3) ? (a == 2) ? 'two' : 'three' : 'four' : 'other';
document.write(a + ' = ' +b);
</script>
<br />
<script>
a = Math.round(Math.random()*4);
b = (a < 5) ? (a < 4) ? (a < 3) ? (a < 2) ? 'one' : 'two' : 'three' : 'four' : 'other';
document.write(a + ' = ' +b);
</script>

the second one works fine as yielding 'yes' to < 3 has to yield yes to the prior clauses too.