How can I remove list item tags where the fields are empty?
<div>
<ul>
<?php
$a = '<li>'.$a.'</li>';
$b = '<li>'.$b.'</li>';
$c = '<li>'.$c.'</li>';
$d = '<li>'.$d.'</li>';
echo $a;
echo $b;
echo $c;
echo $d;
?>
</ul>
</div>
This is a simplified version
答案 0 :(得分:0)
With your example, you should write your php like this:
$result = '';
$result .= '<li>'.$a.'</li>';
$result .= '<li>'.$b.'</li>';
$result .= '<li>'.$c.'</li>';
$result .= '<li>'.$d.'</li>';
echo preg_replace('/<li><\/li>/', '', $result);
答案 1 :(得分:0)
<ul>
<?php
$a = isset($a)?"<li>$a</li>":"";
$b = isset($b)?"<li>$b</li>":"";
$c = isset($c)?"<li>$c</li>":"";
$d = isset($d)?"<li>$d</li>":"";
// echo $a.$b.$c.$d; You can do this
echo $a;
echo $b;
echo $c;
echo $d;
?>
</ul>
Hope that helps!
答案 2 :(得分:0)
I'd use the ternary operator in a function for this.
<div>
<ul>
<?php
$a = build_line_item($a);
$b = build_line_item($b);
$c = build_line_item($c);
$d = build_line_item($d);
echo $a;
echo $b;
echo $c;
echo $d;
function build_line_item($var) {
return !empty($var) ? "<li>{$var}</li>" : '';
}
?>
</ul>
</div>
With this approach you'll only need to make a change in one place if your "empty" definition changes. The current empty rules can be found here, http://php.net/manual/en/function.empty.php.