PHP复杂if语句

时间:2014-07-07 14:07:31

标签: php if-statement

我有一个像这样的PHP if语句:

<?php if(!in_array($_SERVER['SCRIPT_NAME'], array("/page.php", "/", "/index.php", "/design-centre.php"))) { ?>

     //Do Something

<?php } ?>

我正在尝试做的是,如果不是page.php,/,index.php或design-centre.php,如果{。1}仅用于page.php,那么就做一些事情。

2 个答案:

答案 0 :(得分:3)

试试这个:

<?php if (!isset($_GET['action']) && !in_array($_SERVER['SCRIPT_NAME'], array("/page.php", "/", "/index.php", "/design-centre.php"))) { ?>

     //Do Something

<?php } ?>

此代码在if语句中添加!isset($_GET['action']) &&&&运算符意味着您正在进行逻辑AND运算,因此in_array()!isset($_GET['action'])两个语句都必须跳入if

答案 1 :(得分:2)

如果你首先创建一个涉及的pages / url / nodes / etc的数组,我认为会更好......

$pages = array(
    "root" => "/",
    "page" => "/page.php",
    "index" => "/index.php",
    "design-centre" => "/design-centre.php"
);

然后你可以检查当前scriptname是否在pages数组中并且如果它等于pages.php但是查询字符串不是有密钥action

if( !in_array($_SERVER['SCRIPT_NAME'], $pages) AND ( !isset($_GET['action']) AND $_SERVER['SCRIPT_NAME'] == $pages['page']))
{ 
    //Do something
} 

在我看来,最好从if条件中取出你的标准并给它们一个更可读的函数包装器,例如像这样的东西(以程序方式):

$pages = array(
    "root" => "/",
    "page" => "/page.php",
    "index" => "/index.php",
    "design-centre" => "/design-centre.php"
);

function weAreOnMyCriteriaPages($pages)
{
    return in_array($_SERVER['SCRIPT_NAME'], $pages);
}

function weAreOnThisPage($match)
{
    return $_SERVER['SCRIPT_NAME'] == $match;
}

这样您的条件检查将是:

if( !weAreOnMyCriteriaPages($pages) AND ( !isset($_GET['action']) AND weAreOnThisPage($pages['page'])))
{ 
    //Do something
}