Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JussiMannisto's avatar

Referencing other environment variables in .env

Hi,

When defining environment variables in the .env file, is there a way of referencing a variable that was defined earlier? I'd like to do something like this:

INDEX_NAME=dev_index
UPDATE_INDEXER_COMMAND="/some-path/indexer.sh $INDEX_NAME --update"
LIVE_INDEXER_COMMAND="/some-path/indexer.sh $INDEX_NAME --live"
...
0 likes
5 replies
Chris1904's avatar

I don't fully understand, but that's not what env variables are used for.

How about storing them in a config file?

JussiMannisto's avatar

My only goal is to reduce repetition in the .env file. The index name is environment specific, and it is repeated many times in the environment variables.

Of course I can write it out manually on each row, or use a placeholder and insert it in code. But if there's a way of injecting INDEX_NAME to other variables, that would be more elegant.

robrogers3's avatar

that's not how the .env files work.

they are simply read in and parsed as is.

if you need to do something more elegant than try looking at how config works.

i.e.

$foo = config(env('FOO', 'bar')) <-- that way you don't have to put it in .env.

but that also defeats the purpose of keeping things secret.

JussiMannisto's avatar

@robrogers3 That is not true.

Laravel's documentation tells that they use the DotEnv PHP library for environment configuration. From its source code I found out that it supports nested variables, which is exactly what I needed. See the function Dotenv\Loader->resolveNestedVariables for reference.

Here's an example for anyone looking for a solution:

INDEX_NAME=dev_index
UPDATE_INDEXER_COMMAND="/some-path/indexer.sh ${INDEX_NAME} --update"
LIVE_INDEXER_COMMAND="/some-path/indexer.sh ${INDEX_NAME} --live"
11 likes
eyalawardforce's avatar

Note that you need to use the ${VAR} syntax:

MY_KEY=abc
ANOTHER_KEY="${MY_KEY}"
6 likes

Please or to participate in this conversation.