Posted by Marcelo on Sabadini
13/06/2008
Assignment Conditional (Ternary IF)
Assignment Conditional (ternary)
As I said, one of the commands used by a programmer, is undoubtedly the IF. When we do an IF to the assignment of a variable, it is much faster (for programming and performance) using a ternary IF.
The syntax of the IF is thus threefold:
condition? true: false;
It works just like a normal IF. But after? (Mark) is when the condition goes true (true) and after
two points) is when the condition goes false (false).
Here's an example using a normal IF:
$ Age = 18;
if ($ age> 18) {
$ Message = "Greater than age";
Else {}
$ Message = "Underage";
}
See the example IF threefold:
$ Age = 18;
); $ Message = ($ age> 18? "Greater than age": "Underage");
As you can see, is much faster in this case, make an IF ternary.
Note that in this example, I put the ternary brackets, this leaves readability of the code much better.
There are programmers who put each part of the agenda in parentheses. See the example below:
(Condition)? (True) (false)
* You can put a ternary inside another. But, it's very bad to read the code. See the example:
Make a follows: Try to understand these ternary and make them using a normal IF. Post the result here in comments.
Hugs
[UPDATE]
Here the answer to the challenge posted by Diego Tulio:
- <?
- ; $ Age = 17;
- $idade > 18 ) { if ($ age> 18) {
- ; $ Message = "Adult";
- { Else {}
- $idade > 12 ) { if ($ age> 12) {
- ; $ Message = "Teen";
- { Else {}
- ; $ Message = "child";
- }
- }
- ?>



