Is there a shortcut for writing multiple conditions in php?

Is there a shorter way to write (without using regular or string functions)?

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

I am looking for something like:

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

but I know this is wrong. Any suggestions?

+4
source share
5 answers

Try in_array :

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

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

+14
source

Use a switch that is more readable than the complex if condition

 switch ($page){ case 'page1.php': case 'page2.php': case 'page3.php': case 'page4.php': // do something break; default: //else } 
+3
source

To get an answer that is not the same old old:

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

Now it makes sense for your synthetic example, and if you really have ranges of something for testing or some other structure. In most cases, this is just a companion.

+1
source

I think one of the possible solutions is to write a function, since the arguments take page1.php, page2.php, etc. and return true if the statement is correct.

0
source

UPDATE

Sorry for the dead brain response. missed the first line. as stated above, you can create 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 definitely clears the if statement, but doesn't do much to reduce the code. the only advantage I can imagine is that you could build an $ pagelist array from an external source, and use it could be more efficient?

0
source

Source: https://habr.com/ru/post/1391719/


All Articles