? and : operators are in PHP? "Baca juga : Kumpulan arti simbol di php ? "
(($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER)
$x ? $y : $z
$x is true, then use $y; otherwise use $z".?: is "the ternary operator". This is wrong. ?: is a ternary operator, which means that it has three operands. People wind up thinking its name is "the ternary operator" because it's often the only ternary operator a given language has.? : is shorthand for if and else. That's basically it. See "Ternary Operators" half way down this page for more of an official explanation.Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
if statement looks:if (isset($_POST['hello']))
{
$var = 'exists';
}
else
{
$var = 'error';
}
$var = isset($_POST['hello']) ? 'exists' : 'error';
^ ^ ^ ^ |
| then | else |
| | |
if post isset $var=this $var=this
$var in the previous example, but you can also do this with echo, and to check if a variable is false or not:$isWinner = false;
// Outputs 'you lose'
echo ($isWinner) ? 'You win!' : 'You lose';
// Same goes for return
return ($isWinner) ? 'You win!' : 'You lose';
<?php
$array = array(0 => 'orange', 1 => 'multicoloured');
?>
<div>
<?php foreach ($array as $key => $value) { ?>
<span><?=($value==='multicoloured')?'nonsense':'pointless'?></span>
<?php } ?>
</div>
<!-- Outputs:
<span>
pointless
</span>
<span>
nonsense
</span>
-->
if ($isWinner) :
// Show something cool
endif;
if / else statements.- Easy to read
- Easy to understand
- Easy to modify
echo ($colour === 'red') ? "Omg we're going to die" :
($colour === 'blue' ? "Ah sunshine and daisies" :
($colour === 'green' ? "Trees are green"
: "The bloody colour is orange, isn't it? That was pointless."));
- Ridiculously long ternary embedding
- Could've just used a
switchstatement - It was orange in the first place
source
Tidak ada komentar:
Posting Komentar