Twitter icon LinkedIn Icon Github Icon Stackoverflow Icon

Using Multiple Values in a Single .env Entry

By: Roger Creasy

In a recent project I needed to have multiple email addresses in one .env entry. In case you are not familiar with .env, here I am talking about using Vance Lucas' project phpdotenv, which uses a .env file for making values available to a php application. The project somewhat mimics the UNIX concept of environment variables.

In .env files only strings are allowed -- so, an array of values is not a possible answer. Also, I could not have multiple email variables in the .env file because the number of email addresses is unknown.

My solution is to set the value to a comma separated list, then read the values into an array. It is a relatively simple way to handle the problem.

Here is my entry in my .env file:

...
CUSTOMER_ADMIN_EMAILS = address1@example.com, address2@example.com, address3@example.com

...

In the project in which I used this, the .env values are pulled into a settings array, then injected where needed in a container. To simplify this example, I am merely pulling the values directly from the .env file using the php getenv() function.

...

$envRecipients = getenv('CUSTOMER_ADMIN_EMAIL');
$recipients = str_getcsv($envRecipients);

...

The php buit-in function str_getcsv takes a string as input, parses it for values separated by commas, and puts those values in an array.  There are other options for the function; I am just using the defaults here. After parsing the entry, I can access the values as an array. In my case, I used a foreach to loop through the email recipiends and add them to my email->send() method.

Publication Date: 2019-04-17 12:40:39