创建优雅的 if 语句
我有以下一组 if
语句:
<?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>');
?>
我想要一种更优雅的方式来组合这些 if
语句。我尝试过 else if
但显然这只会显示第一个返回 TRUE
的 if
语句,而我想返回每个 >TRUE
声明。我认为 switch
也不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不迭代并使用数组呢?
Why not iterate and use arrays?
也许是一个带有可变变量的 for 循环:
Perhaps a for loop with variable variables:
您应该将其设置为循环,其中值位于数组中。那么只需要一个 if 和一个 echo 语句就可以完成同样的事情。
您甚至不需要 if 语句,因为如果值不存在,您就不会首先将它们添加到 $snList 数组中。
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.
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.
我不确定这会优雅多少,但您可以使用这样的函数:
如果您有这个函数,或者有类似的函数方法可能会有所帮助。
I'm not sure how much more elegant this would be but you could use a function like:
If you have this in more than on place or have something similar the function approach might help.