Question

Is there a shorter way of writing this (without using regex or string-matching functions)?

if($page=='page1.php' || $page=='page2.php' || $page=='page3.php' || $page=='page4.php'){ do something...}

I'm looking for something like:

if($page==('page1.php', 'page2.php', 'page3.php', 'page4.php')){do something...}

but I know that isn't correct. Any suggestions?

Was it helpful?

Solution

Try in_array:

if (in_array($page, array('page1.php', 'page2.php', 'page3.php'))) { ... }

http://php.net/manual/en/function.in-array.php

OTHER TIPS

Use switch, more readable than a complex if condition

switch ($page){
  case 'page1.php':
  case 'page2.php':
  case 'page3.php':
  case 'page4.php':
    // do something
    break;

  default:
    //else
}

To have an answer that is not same old same old:

if (preg_match('"^page[1-4]\.php$"', $page)) {

Now this makes sense for your synthetic example, and if you really have ranges of something to test against, or some other structure to go by. Mostly it just happens to be compacter then.

I think one possible solutions is writing function that as arguments takes page1.php, page2.php etc. and return true if statement is correct.

UPDATE

Sorry for the brain dead answer .. missed the first line. as stated above you could build an array of pages and user in_array()

$pagelist = array('page1.php','page2.php','page3.php','page4.php','page5.php')
if (in_array($page,$pagelist)) {
    //do something
}

it's a bit more elegant and definately cleans up the if statement, but doesn't do much to reduce the code. the only benefit i can think is that you could build the $pagelist array from an external source and using it might be more efficient?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top