<variable> = <expression> ? <value> : <value>

» 15 April 2007 » In PHP »

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

$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:


Tags:

Tags:

Trackback URL

One Comment on "<variable> = <expression> ? <value> : <value>"

Hi Stranger, leave a comment:

*

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to Comments