Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to simplify this case statement?

I have this PHP case statement

switch ($parts[count($parts) - 1]) {
    case 'restaurant_pos':
        include($_SERVER['DOCUMENT_ROOT'] . '/pages/restaurant_pos.php');
        break;
    case 'retail_pos':
    include($_SERVER['DOCUMENT_ROOT'] . '/pages/retail_pos.php');
        break;  
    .....

}

Which works great but I have many many files (like 190) and I would love to know if there is a way to make this case statement many work with anything so I dont have to do 190 case conditions. I was thinking I can use the condtion in the case and maybe see if that file is present and if so then display and if not then maybe a 404 page but i was not sure a good way to do this...any ideas would help alot

like image 758
Matt Elhotiby Avatar asked Jul 25 '11 15:07

Matt Elhotiby


People also ask

What is simple case statement?

The simple CASE statement evaluates a single expression and compares it to several potential values. The searched CASE statement evaluates multiple Boolean expressions and chooses the first one whose value is TRUE .

How do you write a case statement?

The case statement should include your mission, vision and values statements, and should set out to clearly answer the who, what, and why of your fundraising efforts. The Alaska Food Coalition offers some questions that an effective case statement might seek to answer: - How does this organization help people?

How do you end a case statement?

The CASE statement ends with an END keyword.

Can you use a select in a case statement?

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well.


2 Answers

You can predefine file names in an array and then use in_array in order to check name's existence:

$files = array('restaurant_pos', 'retail_pos', ......);
$file = $parts[count($parts) - 1];
if (in_array($file, $files)) {
    include($_SERVER['DOCUMENT_ROOT'] . "/pages/$file.php");
}
like image 199
Karolis Avatar answered Sep 19 '22 22:09

Karolis


If it's not user input, you can do it like

$include = $parts[count($parts) - 1];
if ($include) {
    if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/pages/'.$include.'.php')){
          include $_SERVER['DOCUMENT_ROOT'] . '/pages/'.$include.'.php';
    }
}

repeating, don't do this if $include is being filled from user's input !

like image 22
genesis Avatar answered Sep 16 '22 22:09

genesis