One Line If...Else Statements for Variables
Views: 5781
Comments: 0
Posted: 8-1-2008
based on 0 votes.
Faves: 0 | + Faves
Page(s): 1 2 Next Page
Quickly Assign Variables a Value In One Line Using If...Else in PHP

Do you have a code like this:
1
2
3
4
<?
if($hour < 12) { $greeting = "Good morning!"; }
else { $greeting = "Good afternoon!"; }
?>

Did you know that you can shorten that code into a single line with a simple PHP format?

The format is below, and each part is explained in the paragraphs following.  Seeing as the code example at the beginning of the tutorial is fairly easy to understand and infer the purpose of, we're going to use that.

1
2
3
4
5
<?
$
[VarName] = ([If]) ? [IfTrue] : [IfFalse];
// The following is what the example at the beginning of the tutorial would look like.
$
greeting = ($hour < 12) ? "Good morning!" : "Good afternoon!";
?>

[VarName] The name of the variable that you want the output to be placed in.  For the example, it is greeting.

[If] The if statement your wanting to put the variable through.  It has to be in parentheses!  For the example, it is ($hour < 12).

[IfTrue] The variable's value if the if statement is true.  For the example, it is "Good morning!".

[IfFalse] The variable's value if the if statement is false.  For the example, it is "Good afternoon!".


Continue onto the next page to see various examples of this function in action!

Page(s): 1 2 Next Page
More tutorials from this author:

» A Helpful Tutorial on require_...

View All Tutorials
Rcty - http://tip.it/runescape/
Hi!

I don't write many tutorials, and I'm really good at getting into PHP problems that even my really experienced PHP coding friends have to scour to find! However, I promise that I put legit content on my tutorials. :)
Close