简体   繁体   中英

Simplify checking multiple PHP-pages in If-statement using array

Problem:

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

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?

Yes you're right, you can reduce code by putting all pages in array & check using 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';
}

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:

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:

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM