使用PHP编写“if”条件语句的不同方法有哪些?

时间:2009-10-20 13:14:22

标签: php

使用PHP编写条件语句有哪些不同的写法?

我知道以下

的例子
if($test == 1){
}else{
}

if($test == 1)
   echo 'asdsa';
else
   echo 'sdaaa';

8 个答案:

答案 0 :(得分:11)

alternative control structure syntax

if ($text == 1):
    echo 'asdsa';
else:
   echo 'asdsa';
endif;

答案 1 :(得分:8)

另一种方法是使用ternary operator。 PHP文档中的示例是:

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>

另一个control structures are documented in the PHP manual。唯一的条件语句是三元条件运算符if(和else),elseifelse if。但是,他们确实有an alternative syntax

答案 2 :(得分:6)

echo ($test == 1) ? 'asdsa' : 'sdaaa';

答案 3 :(得分:4)

除了已经说过的内容之外,还有像

这样的东西
$sql_link = mysql_connect('localhost', 'root') or die('no mysql');

或者像Alternative syntax for control structures

一样

(赋值“OR”技巧实际上是一招)如果mysql_connect()没有变为true,PHP会尝试评估第二个表达式,所以这真的是一个黑客:

if (mysql_connect('localhost', 'root')) {
    $sql_link = true;
}
else {
    die('no mysql');
}

答案 4 :(得分:3)

不要忘记“条件复杂性”是一种代码气味。 Polymorphism是你的朋友。

  

条件逻辑在其初期是无辜的,当它易于理解并包含在其中时   几行代码。不幸的是,它很少老化。您实现了几个新功能   突然你的条件逻辑变得复杂和膨胀。 [Joshua Kerevsky:重构模式]

你可以做的最简单的事情之一是避免嵌套if块学会使用Guard Clauses。 (注意:这不是PHP语法。将其视为伪代码。这里的技术非常重要。)

double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};  

我发现的另一件事情很简单,它使你的代码自我记录,是Consolidating conditionals

double disabilityAmount() {
    if (isNotEligableForDisability()) return 0;
    // compute the disability amount

与条件表达式相关的其他有价值的refactoring技术包括Decompose ConditionalReplace Conditional with VisitorReverse Conditional

既然你有一些新的锤子,不要让一切看起来像钉子!

答案 5 :(得分:3)

标准if语句:

if(expression) {
    // code
} elseif(expression) {
    // code
} else {
    // code
}

在每个语句后没有用于单行代码的大括号:

if(expression)
    // single line of code
elseif(expression)
    // single line of code
else
    // single line of code

备用控制语法:

if(expression):
    // code
elseif(expression):
    // code
else:
    // code
endif;

最后,三元运营商:

(expression ? expression_if_true : expression_if_false);

也可以写成:

(expression) ? expression_if_true : expression_if_false;

如果您愿意,可以完全没有括号。

答案 6 :(得分:2)

if($test == 1){
}else{
}

# can only be used if performing 1 line of code after statement
if($test == 1)
   echo 'asdsa';
else
   echo 'sdaaa';

#you can have as many elseif as you like (but you may wish to check out switch see below:
if($test == 1){
}elseif{
}else{
}

另请查看switch() http://php.net/manual/en/control-structures.switch.php

switch($test)
{
    case "1" :
        break;
    case "2" :
        break;
    default :
        break;
}

答案 7 :(得分:1)

直接来自PHP manual

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?> 
相关问题