Convert elses to switch with boolean return value
I'm trying to convert this simple set of else statements into a more readable switch;
$parts_arr = explode('.', $_SERVER['SERVER_NAME']);
if (in_array('dev', $parts_arr)) {
DEFINE('APP_ENV', "dev");
} else if (in_array('staging', $parts_arr)) {
DEFINE('APP_ENV', "staging");
} else if (in_array('local', $parts_arr)) {
DEFINE('APP_ENV', "local");
} else {
DEFINE('APP_ENV', "live");
}
However, I have drawn the blank completely. I cannot use a foreach loop and use a string as an argument as APP_ENV
it cannot be overridden.
+3
source to share
4 answers
You can only check the name of the entire server.
switch($_SERVER['SERVER_NAME']) {
case 'mysite.com':
case 'www.mysite.com':
DEFINE('APP_ENV', "live");
break;
case 'dev.mysite.com':
DEFINE('APP_ENV', "dev");
break;
case 'staging.mysite.com':
DEFINE('APP_ENV', "staging");
break;
case 'mylocalhost.local':
DEFINE('APP_ENV', "local");
break;
default:
exit;
}
+1
source to share
You cannot turn it into a switch case structure unless you do an inkjet comparison.
Perhaps something like this:
$str = array_pop(explode('.', $_SERVER['SERVER_NAME']));
switch($str)
{
case 'dev' :
DEFINE('APP_ENV', "dev");
break;
// en so on
}
Sunil Pachlangia's solution won't work because it compares an array and a string
0
source to share
<?php
$parts_arr = explode('.', $_SERVER['SERVER_NAME']);
switch (true) {
case in_array('dev', $parts_arr):
DEFINE('APP_ENV', "dev");
break;
case in_array('staging', $parts_arr):
DEFINE('APP_ENV', "staging");
break;
case in_array('local', $parts_arr):
DEFINE('APP_ENV', "local");
break;
default:
DEFINE('APP_ENV', "live");
break;
}
0
source to share
I think I would avoid splitting strings and parsing array elements as @ Almo-Do commented. Be specific in some config file.
$environments = array(
'localhost' = > 'local'
, 'staging.mysite.com' > 'staging'
// etc - see? now you can comment some out
//, 'mysite.com' => 'live'
);
Then just
define ('APP_ENV', $environments[$_SERVER['SERVER_NAME']]);
Or even be a little more protective before that, something like:
if (!array_key_exists($environments[$_SERVER['SERVER_NAME'])) die('suitable msg');
0
source to share