We all know that you as a programmer often is in a situation, where you proberly use an if-else construction. But you don’t always have to, often it is more sophisticated to use the sentence from the title and assign the right value, when the variable is instantiated.
<variable> = <expression> ? <value> : <value>
Let me give an example “when the sky is dark, then daytime is night, otherwise daytime is day”.
[source:php]
< ?php
$sky = “Dark”;
if(strcmp($sky, “Dark”) == 0) {
$day_time = “Night”;
}
else {
$day_time = “Day”;
}
?>
[/source]
The piece of code where you assign a value to “day_time” could you easily write on line:
[source:php]
< ?php
$sky = “Dark”;
$day_time = strcmp($sky, “Dark”) == 0 ? “Night” : “Day”;
?>
[/source]
So keep this little trick in mind, whenever a variable can be assigned one of two possible values.
Possibly Related Posts:
- Yay, going to the IPC 2008!
- Light-weight PHP engine for BPEL based on XML-rewriting
- Diploma Project handed in, Yay!
- Understanding the PHP object model (slides)
- What PHP IDE to choose? There are so many out there….