user1592380
user1592380

Reputation: 36227

php ternary operator explanation

I am confused. I had set up the following code in my index.php to auto switch between xampp and server database config files:

define('ENVIRONMENT', isset($_SERVER['SERVER_NAME'])=='my_domain_name.com' ? 'production' : 'development');

    echo 'SERVER_NAME  '.$_SERVER['SERVER_NAME']; // getting localhost
    echo 'env '.ENVIRONMENT; // getting production.

In Xampp locally, I thought this would result in the ENVIRONMENT constant set to 'development' with $_SERVER['SERVER_NAME']=localhost. Would someone mind explaining what I'm doing wrong here?

Upvotes: 0

Views: 95

Answers (3)

Cat
Cat

Reputation: 67502

define('ENVIRONMENT', isset($_SERVER['SERVER_NAME'])=='my_domain_name.com' ? 'production' : 'development');

Here you're comparing the result of isset() to 'my_domain_name.com'; you're comparing a boolean to a string.

What you want is to check "is $_SERVER['SERVER_NAME'] set AND is $_SERVER['SERVER_NAME'] equal to my_domain_name.com?", as follows:

define('ENVIRONMENT', (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] == 'my_domain_name.com') ? 'production' : 'development');

(Or... just remove the isset() entirely.)

Upvotes: 3

Isaac
Isaac

Reputation: 2721

Try this:

define('ENVIRONMENT', ((isset($_SERVER['SERVER_NAME']) && ($_SERVER['SERVER_NAME']=='my_domain_name.com')) ? 'production' : 'development'));

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102743

You don't need to use isset in this case (you know it's set already):

define('ENVIRONMENT', 
    ($_SERVER['SERVER_NAME']) == 'my_domain_name.com' ? 'production' : 'development'
);

Upvotes: 1

Related Questions