如何编写if条件部分


how to write the if condition part?

以下有一些链接

    https://example.com/cart.php
    https://example.com/cart.php?gid=1
    https://example.com/cart.php?gid=2
    https://example.com/cart.php?a=view
    https://example.com/cart.phpcart.php?a=confproduct&i=0
.......

我想在那些链接页面上添加一些文本。如何编写if条件?

if($_SERVER['REQUEST_URI']=='/cart.php'||......)

有简单的方法吗?

字符串比较怎么样?

$mystr = "https://example.com/cart.php";
if (0 != strncmp($_SERVER['REQUEST_URI'], $mystr, strlen($mystr)) { ... }

strncmp只比较前n个字符;我们通过CCD_ 1进行计数。

使用$_SERVER['PHP_SELF'],如下所示:

if($_SERVER['PHP_SELF'] == "/cart.php"){
    // do stuff
} elseif($_SERVER['PHP_SELF'] == "/anotherpage.php"){
    // do other stuff
}

将它们放在一个数组中,然后使用in_array()

$pages = array(
   '/cart.php',
   '/cart.php?gid=1',
   '/cart.php?gid=2',
   '/cart.php?a=view'
);
if(in_array($_SERVER['REQUEST_URI'], $pages)) {
   // ...
}

如果你的链接不是太多,你可以使用@zhuanzhou说的方法。

否则,为什么不在uri中添加一个新的参数,比如

https://example.com/cart.php?rule=1
https://example.com/cart.php?gid=1&rule=1
https://example.com/cart.php?gid=2&rule=1
https://example.com/cart.php?a=view&rule=1

那么,你的代码可以是:

if($_GET['rule'] === 1){
// something here
}