I'm looking to add an if statement to display a title if something is in a variable but not 100% sure how to go about it.
My current coding s开发者_运维问答hows:
<?php echo $quote->getmessage(); ?>
But I would like it to show a title and the content of the message if there is content in the variable. If there is nothing within the variable I don't want to show anything.
IMHO it's better to be as verbose as necessary so that the code is easily readable and can be extended without totally rewriting it:
<?php
$message = $quote->getmessage();
if (!empty($message)) {
echo "Title!";
echo htmlspecialchars($message);
}
?>
Use php's isset function to check if a variable is set, and empty to see if it's empty.
For instance
<?php $a = $quote->getmessage();if (!empty($a)) echo $a; ?>
<?php echo ($quote->getmessage() == "") ? "" : "Title <br />".$quote->getmessage(); ?>
Use a ternary operator:
<?php
$quote_var = $quote->getmessage();
echo ($quote_var != null)?$quote_var:'NOTHING!';
//displays 'NOTHING' if the variable is null
?>
<?php
$mssg = $quote->getmessage();
echo (!empty($mssg))?$mssg:'';
?>
If you want your line to be concise, then I would advise this syntax:
<?php $msg = $quote->getmessage() AND print "<h6>title</h6>$msg"; ?>
The AND
has a lower precedence than the assignment (but extra whitespace or braces make that more readable). And the second part only gets executed if the $msg
variable receives any content. And print
can be used in this exporession context instead of echo
.
<?php
if(isset($quote->getmessage())
{
echo "My Title";
}
?>
精彩评论