user3886840
user3886840

Reputation: 53

Dont show if field is left blank

This is the code that shows a Manufacturer Part Number on my product listing

<span class="p-rewards">MPN:<?php echo $text_mpn; ?></span> <?php echo $mpn; ?><br />

what I would like to do is not show the MPN: Field on the product page if the $text_mpn field is blank, e.g if no part number is listed.

Upvotes: 0

Views: 80

Answers (5)

Ram Pukar
Ram Pukar

Reputation: 1621

<?php 
$mpn = 'Ram Pukar';
$text_mpn = 'Hello ';
echo $text = !empty($mpn) ? '<span class="p-rewards">MPN: '.$text_mpn.'</span>'.$mpn.'<br />':null;
?>

Output:

MPN: Hello Ram Pukar

Upvotes: 0

Vasim Shaikh
Vasim Shaikh

Reputation: 4512

Case 1: You can use empty() for check is variable is empty or not.

<?php if(empty($mpn)){ ?>
<span class="p-rewards">MPN:<?php echo $text_mpn; ?></span> <?php echo $mpn; ?><br />
<?php } ?>

Case :2

You can simply use display:none if you wants to hide control.you can simply add attribute of style.

  <div <?php if(empty($mpn))
    { echo 'style="display:none"';}
   else {echo 'style="display:block"';}
    ?> >
    <span class="p-rewards">MPN:<?php echo $text_mpn; ?></span> <?php echo $mpn; ?><br />
 </div>

Upvotes: 0

WowThatsLoud
WowThatsLoud

Reputation: 113

try this

<?php if(strlen($text_mpn) > 0) echo "<span class='p-rewards'>MPN:".$text_mpn."</span>".$mpn."</br>"; ?>

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116110

You can put an if statement around it. You can close the PHP code block after the if, put your code inbetween and open a new PHP code block to close it:

<?php if ($text_mpn != ''){ ?>
<span class="p-rewards">MPN:<?php echo $text_mpn; ?></span> <?php echo $mpn; ?><br />
<?php };>

For blocks like this, it can be a bit messy and unclear to see where the block ends if you use normal curly braces, so you might consider the Alternative syntax for control structures for these cases:

<?php if ($text_mpn != ''):?>
<span class="p-rewards">MPN:<?php echo $text_mpn; ?></span> <?php echo $mpn; ?><br />
<?php endif;>

Upvotes: 1

Sam Teng Wong
Sam Teng Wong

Reputation: 2439

try this:

<?php if($mpn != ""){ ?>
  <span class="p-rewards">MPN:<?php echo $text_mpn; ?></span> <?php echo $mpn; ?><br />
<?php } ?>

Upvotes: 0

Related Questions