Saturday, November 13, 2004

PHP if ... elseif ... else ...

Sample code:

<?php

$temperature = 0; // degrees celsius

if ($temperature == 0) {
print("I am freezing.");
} elseif ($temperature == 100) {
print("I am boiling.");
} else {
print("In between boiling and freezing points.");
}

?>

prints

I am freezing.

Shortcut using the ternary operator:

If there are only two possible alternatives, you can use the ternary operator as a shortcut:

eg.

<?php

$reply = 1;

if ($reply == 1) {
$result = "yes";
} else {
$result = "no";
}

print($result);

?>

is the same as :

<?php

$reply = 1;
$result = (($reply == 1)? "yes" : "no");
print($result);

?>

0 Comments:

Post a Comment

<< Home