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];
$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!