I have the following set of if
statements:
<?php
if (!empty($sn1link) && !empty($sn1)) {
echo('<a href="'.$sn1link.'" target="_blank"><button class="lbutton-content">'.$sn1.'</button></a>');
}
if (!empty($sn2link) && !empty($sn2)) {
echo('<a href="'.$sn2link.'" target="_blank"><button class="lbutton-content">'.$sn2.'</button></a>');
}
if (!empty($sn3link) && !empty($sn3)) {
echo('<a href="'.$sn3link.'" target="_blank"><button class="lbutton-content">'.$sn3.'</button></a>');
}
if (!empty($sn4link) && !empty($sn4)) {
echo('<a href="'.$sn4link.'" target="_blank"><button class="lbutton-content">'.$sn4.'</button></a>');
}
if (!empty($sn5link) && !empty($sn5)) {
echo('<a href="'.$sn5link.'" target="_blank"><button class="lbutton-content">'.$sn5.'</button></a>');
?>
I would like a more elegant way of combining these if
statements. I've tried else if
but obviously this would only display the first if
statement that returns TRUE
whereas I'd like to return every TRUE
statement. I don't think a switch
would work either.
Why not iterate and use arrays?
foreach($sn_array as $link => $text):
if(!empty($link) && !empty($text)) echo ...;
endforeach;
Perhaps a for loop with variable variables:
<?php
for ($i = 1; $i <= 5; $i++) {
$link = 'sn'.$i.'link';
$button = 'sn'.$i;
if (!empty($$link) && !empty($$button)) {
echo('<a href="'.$$link.'" target="_blank"><button class="lbutton-content">'.$$button.'</button></a>');
}
}
you should make it a loop, where the values are in an array. then only one if, and one echo statement are needed to accomplish the same thing.
$snList = array($sn1 => $sn1Link, $sn2 => $sn2Link, $sn3 => $sn3Link);
foreach ($snList as $name => $link) {
echo('<a href="'.$link.'" target="_blank"><button class="lbutton-content">'.$name.'</button></a>');
}
you don't even need the if statement, because if the values don't exist, you simply don't add them to the $snList array in the first place.
$snList = array();
$snList[$key] = $value;
I'm not sure how much more elegant this would be but you could use a function like:
function getButtonContent($link, $content) {
if (!empty($link) && !empty($content)) {
echo('<a href="'.$link.'" target="_blank"><button class="lbutton-content">'.$content.'</button></a>');
}
}
getButtonContent($sn1link, $sn1);
getButtonContent($sn2link, $sn2);
getButtonContent($sn3link, $sn3);
etc....
If you have this in more than on place or have something similar the function approach might help.