在PHP中使用或不使用大括号的重要或含义是什么?

时间:2017-04-30 19:28:52

标签: php curly-braces control-structure

我只是想知道使用或不使用花括号编写PHP代码段是否有原因或优势。

我有这三种方法来获得数字的序数后缀。在这种情况下,最佳方法应该是什么

方法1:没有"大括号" "花括号"

function ordinalSuffix($n) {
    //any number such as zero(0) should end with 'th' other than 1,2,3 which must be 1st 2nd 3nd
    $appends = array('th','st','nd','rd','th','th','th','th','th','th');
    // using php modulus check if number is 11, 12 or 13 
    if ((($n % 100) >= 11) && (($n % 100) <= 13))
        return $n. 'th'."<br/>";
    else
           return $n. $appends[$n % 10]."<br/>";
}
//Example Usage
$studentMarks=range(1,26);
foreach($studentMarks as $key => $studentResult)
//check for odd and even
if(($key % 2) == 1)
echo "<div class='dark'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>";
else 
echo "<div class='ligth'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>";

方法2:没有&#34;大括号&#34; &#34;花括号&#34;

function ordinalSuffix($n) {
    //any number such as zero(0) should end with 'th' other than 1,2,3 which must be 1st 2nd 3nd
    $appends = array('th','st','nd','rd','th','th','th','th','th','th');
    // using php modulus check if number is 11, 12 or 13 
    if ((($n % 100) >= 11) && (($n % 100) <= 13)):
        return $n. 'th'."<br/>";
    else:
           return $n. $appends[$n % 10]."<br/>";
    endif;
}
//Example Usage
$studentMarks=range(1,26);
foreach($studentMarks as $key => $studentResult):
//check for odd and even
if(($key % 2) == 1):
echo "<div class='dark'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>";
else: 
echo "<div class='ligth'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>";
endif;
endforeach; 

方法3:使用&#34;大括号&#34; &#34;花括号&#34;

function ordinalSuffix($n) {
    //any number such as zero(0) should end with 'th' other than 1,2,3 which must be 1st 2nd 3nd
    $appends = array('th','st','nd','rd','th','th','th','th','th','th');
    // using php modulus check if number is 11, 12 or 13 
    if ((($n % 100) >= 11) && (($n % 100) <= 13)){
        return $n. 'th'."<br/>";
    }
    else{
           return $n. $appends[$n % 10]."<br/>";
    }
}
//Example Usage
$studentMarks=range(1,26);
foreach($studentMarks as $key => $studentResult){
//check for odd and even
if(($key % 2) == 1){
echo "<div class='dark'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>";
}
else{ 
echo "<div class='ligth'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>";
}
}

1 个答案:

答案 0 :(得分:1)

然后你 从不 必须担心作为条件的一部分执行什么代码。不要让你的未来自己,或任何维护这些代码的人,做出一个愚蠢的,可以预防的错误。所需要的是在没有支撑的情况下向IF语句添加一行,并且出现意外,难以捕获的错误。它也更容易阅读。可维护性始终很重要,不应忽视。