This is from a tutorial for php, I cant understand the use of the ternary ? And the use of the colon : Can you please explain to me the use of the colon in here thanks I tried to read the tutorial and php reference but couldn't understand it
This code will print a side way pyramid
for ($row = 1; $row <= 5; $row++)
{
for ($col = 1; $col <= ($row > 3 ? 6 - $row : $row); $col++)
{
echo '*';
}
echo "<br>";
}
This is the same as the following code:
for ($row = 1; $row <= 5; $row++)
{
if ($row > 3)
$max = 6 - $%row;
else
$max = $row;
for ($col = 1; $col <= $max; $col++)
{
echo '*';
}
echo "<br>";
}
The colon is part of the ternary operator:
A ? B : C
equals to
if (A) then B else C
For more information please check the documentation on the ternary (?:
) operator.
ternary if:
/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns tru
Makes coding simple if/else logic quicker You can do your if/else logic inline with output instead of breaking your output building for if/else statements Makes code shorter Makes maintaining code quicker, easier
read below article for more examples:
https://davidwalsh.name/php-shorthand-if-else-ternary-operators