使用数组简化在If语句中检查多个PHP页面

时间:2022-11-11 18:03:45

Problem:

Optimizing PHP code to print code upon arrival to one of multiple pages.

优化PHP代码,在到达多个页面之一时打印代码。

PHP-code:

if (substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-c.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-g.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-j.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-n.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-q.php")
{
    echo 'Hello';
}

Suggestion:

I'm thinking whether it is a good idea to put all pages in an array and check if the page you are in exist in that array. Other suggestions how this can be solved?

我在想是否将所有页面放在一个数组中并检查您所在的页面是否存在于该数组中是一个好主意。其他建议如何解决这个问题?

2 个解决方案

#1


2  

Yes you're right, you can reduce code by putting all pages in array & check using in_array.

是的,你是对的,你可以通过将所有页面放在数组中并使用in_array进行检查来减少代码。

$checkString = substr(strrchr($_SERVER['PHP_SELF'], '/'), 1);
$pages = array("part-c.php","part-g.php","part-j.php","part-n.php","part-q.php");

if(in_array($checkString,$pages)){
   echo 'Hello';
}

#2


0  

You can also put your files in a txt file which is only read by the server setting it to CHMOD 0664, then list the files like so:

您也可以将文件放在一个txt文件中,该文件只能由服务器将其设置为CHMOD 0664来读取,然后列出这样的文件:

vPages.txt

part-c.php
part-g.php
part-j.php
part-n.php
part-q.php

and then run some code like Rikesh suggested:

然后运行像Rikesh建议的一些代码:

$page = substr( strrchr( $_SERVER['PHP_SELF'], '/' ), 1 );
$vPages = file( './vPages.txt' );

if ( in_array( $page, $vPages ) ) {
    // Seems legit...

}

and you'll be able to easily edit a file to include more valid pages.

并且您将能够轻松编辑文件以包含更多有效页面。

#1


2  

Yes you're right, you can reduce code by putting all pages in array & check using in_array.

是的,你是对的,你可以通过将所有页面放在数组中并使用in_array进行检查来减少代码。

$checkString = substr(strrchr($_SERVER['PHP_SELF'], '/'), 1);
$pages = array("part-c.php","part-g.php","part-j.php","part-n.php","part-q.php");

if(in_array($checkString,$pages)){
   echo 'Hello';
}

#2


0  

You can also put your files in a txt file which is only read by the server setting it to CHMOD 0664, then list the files like so:

您也可以将文件放在一个txt文件中,该文件只能由服务器将其设置为CHMOD 0664来读取,然后列出这样的文件:

vPages.txt

part-c.php
part-g.php
part-j.php
part-n.php
part-q.php

and then run some code like Rikesh suggested:

然后运行像Rikesh建议的一些代码:

$page = substr( strrchr( $_SERVER['PHP_SELF'], '/' ), 1 );
$vPages = file( './vPages.txt' );

if ( in_array( $page, $vPages ) ) {
    // Seems legit...

}

and you'll be able to easily edit a file to include more valid pages.

并且您将能够轻松编辑文件以包含更多有效页面。