Control Flow Details
Ternary Choice
The ternary operator chooses between two expressions.
ternary
`condition ? a : b` returns `a` when the condition is true, otherwise `b`.
Ternary Choice
ternary_choice.php
Replay: real traced execution (multi-file project)
<?php
$age = 18;
$ticket = $age >= 18 ? "adult" : "child";
$price = $ticket === "adult" ? 12 : 6;
echo "age=" . $age . "\n";
echo "ticket=" . $ticket . "\n";
echo "price=" . $price . "\n";
<?php
$age = 12;
$ticket = $age >= 18 ? "adult" : "child";
$price = $ticket === "adult" ? 12 : 6;
echo "age=" . $age . "\n";
echo "ticket=" . $ticket . "\n";
echo "price=" . $price . "\n";
<?php
$age = 30;
$ticket = $age >= 18 ? "adult" : "child";
$price = $ticket === "adult" ? 12 : 6;
echo "age=" . $age . "\n";
echo "ticket=" . $ticket . "\n";
echo "price=" . $price . "\n";
$age ← 18, $ticket ← adult, $price ← 12
1<?php2$age→ 18 = 18; //@age=12, 303$ticket→ adult = $age18 >= 18 ? "adult" : "child";4$price→ 12 = $ticketadult === "adult" ? 12 : 6;56echo "age=" . $age18 . "\n";7echo "ticket=" . $ticketadult . "\n";8echo "price=" . $price12 . "\n";outputage=18 ticket=adult price=12
$age ← 12, $ticket ← child, $price ← 6
1<?php2$age→ 12 = 12;3$ticket→ child = $age12 >= 18 ? "adult" : "child";4$price→ 6 = $ticketchild === "adult" ? 12 : 6;56echo "age=" . $age12 . "\n";7echo "ticket=" . $ticketchild . "\n";8echo "price=" . $price6 . "\n";outputage=12 ticket=child price=6
$age ← 30, $ticket ← adult, $price ← 12
1<?php2$age→ 30 = 30;3$ticket→ adult = $age30 >= 18 ? "adult" : "child";4$price→ 12 = $ticketadult === "adult" ? 12 : 6;56echo "age=" . $age30 . "\n";7echo "ticket=" . $ticketadult . "\n";8echo "price=" . $price12 . "\n";outputage=30 ticket=adult price=12
Pick Ticket and Price
$agestarts at18.$age >= 18is true, so ticket becomesadult.- The second ternary sees
adult. - The price becomes
12. | Age | Ticket | Price | | --- | --- | --- | |12|child|6| |18|adult|12| |30|adult|12|
Exercise: ternary_choice.php
Use ternary expressions to choose child or adult ticket text and price