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

socieboy's avatar

Return array from .env

On L4 i used to return arrays from my .env.php config files...

<?php 
return [
    'key' => [
        'other key' => 'value',
        'other key' => 'value'
    ];
];
?>

Now in L5 I don't use the ext .php for those files, I leave just like .env.

How do I get return an array from this .env file?

KEY=[ otherkey=>value, other_key => value];

0 likes
28 replies
tjames's avatar

@socieboy You can't do what you're wanting to do with the .env files, the library doesn't support it. You'll either have to move your array to a config file or do something like this:

KEY=val
KEY_KEY1=val
KEY_KEY2=val
socieboy's avatar

@tjames I need the KEY return an array!! something like

KEY = [
    [0]  => 'Value 1',
    [1] => 'Value 2',
];

I could do that on L4, with the .env.php but not with L5.

1 like
davorminchorov's avatar

In your config file, return an array and replace the values with env('VARIABLE_NAME');

return [     
    env('KEY') => [
        env('KEY_ONE') => env('VALUE_ONE'),     
        env('KEY_TWO') => env('VALUE_TWO')  
    ]
};

Add KEY, KEY_ONE, KEY_TWO, VALUE_ONE, VALUE_TWO in your ,env file and it should work.

KEY=VALUE
KEY_ONE=VALUE_ONE
KEY_TWO=VALUE_TWO
3 likes
tjames's avatar

@socieboy I understand that's what you want to do, but it is NOT possible with the .env files. Laravel 5 uses the vlucas/phpdotenv library for parsing the .env files. That library does not support arrays in the .env files. So like I said, you will either have to move the array to a config file or find some other method to do what you want to do.

michaeldyrynda's avatar

Environment variables aren't really designed for arrays. You can put a delimited list and explode it out in your AppServiceProvider, then put it back into your environment, but that's as close as you'll get I'm afraid.

Ultimately, environment variables are just key/value pairs.

9 likes
socieboy's avatar

Thank you for the information @deringer for my proposes i would like to store the key that i need to return as array, and also I don't like the idea to store on a config file those keys. I was happy on L4 when i could return and ENV var with an array values.

martinbean's avatar

@socieboy Environment variables are meant to be simple key-value pairs of strings.

Yes, in Laravel 4 you could define whatever data you wanted but that’s because configuration was array-based and not environment variable-based.

Instead, you should prefix your variable keys like say, the MAIL_ variables are: MAIL_HOST, MAIL_USERNAME etc.

I’d be interested to know what use case you have where you need an array returned, instead of defining your configuration variables as above.

socieboy's avatar

@martinbean I made a Class to manage my subscriber users and send emails using mailchimp

class Notifier implements NotifierInterface{

protected $lists = [
    'mailing-list' => 'mailchimp-list-id',
    'other-list ' => 'other-id'
];

protected $mailchimp;

I just don't wanna define my ID's on here, I want to create a .ENV to return the array....

protected $lists = env('MAILCHIMP_LIST_')
martinbean's avatar

@socieboy You’re probably better off defining them in config/services.php instead:

<?php
return [
    'mailchimp' => [
        'mailing_list' => 'ABC',
        'other_list' => 'DEF',
    ],
];

The .env file is more for sensitive information, such as your MailChimp API keys.

carsonevans's avatar

I accomplish this with JSON strings.

SETTING={"KEY1":"VALUE1","KEY2":"VALUE2"}

And then use json_deocde on it.

$mydata = (array)json_decode(env('SETTING'));

I typically don't do the typecasting and leave $mydata as an object though.

12 likes
158ltd's avatar

@carsonevans this looks nice. You can avoid typecasting by passing second argument to json_decode($json, true);.

Here is what I did:

# .env
MY_ENV_ARRAY=first,second,third

# config/app.php (or create your own config file)
'MY_ENV_ARRAY' => explode(env(',', 'VARIABLE_NAME'))

or we can use the JSON approach by @carsonevans:

# .env
MY_ENV_ARRAY="{\"first_key\": \"first\", \"second_key\": \"second\", \"third_key\": \"third\"}"

# config/app.php (or create your own config file)
'MY_ENV_ARRAY' => json_decode(env('MY_ENV_ARRAY'), true)

Don't forget to put the JSON in quotes and escape all quotes inside.

9 likes
orrd's avatar

For anyone else who finds this thread, there seems to be a typo in the comma-separated example. It should be this in the config file:

'MY_ENV_ARRAY' => explode(',', env('VARIABLE_NAME'))

You may also want to trim spaces from the items as well like this:

'MY_ENV_ARRAY' => array_map('trim', explode(',', env('VARIABLE_NAME')))
3 likes
orlissenberg's avatar

Or something like this:

if (! function_exists('env_array')) {
    /**
     * Gets the values of an environment array.
     *
     * @param string $name
     * @param bool $flatten
     * @param array $default
     * @return array
     */
    function env_array(string $name, bool $flatten = true, array $default = []): array
    {
        $data = [];
        foreach ($_ENV as $key => $value) {
            $matches = [];
            if (preg_match('/^' . $name . '\[([a-zA-Z0-9]*)\]$/', $key, $matches)) {
                if (isset($matches[1])) {
                    $data[$matches[1]] = $value;
                }
            }
        }

        if (empty($data)) {
            $data = $default;
        }

        if ($flatten) {
            return array_values($data);
        }

        return $data;
    }
}

var_dump(env_array('SCOUT_HOST'));
var_dump(env_array('SCOUT_HOST', false));
var_dump(env_array('SCOUT_HOST', false, ['foo' => 'bar']));
var_dump(env_array('SCOUT_HOSTS', false, ['foo' => 'bar']));
var_dump(env_array('SCOUT_HOSTS', true, ['foo' => 'bar']));

.env

SCOUT_HOST[1]=localhost:9200
SCOUT_HOST[2]=localhost:9201
SCOUT_HOST[another]=localhost3:9202
wesamly's avatar

In .env file:

MY_KEY=key1|value1,key2|value2

In config/sample.php

return [
'key' => collect(explode(',', env('MY_KEY', [])))->pipe(function($collection) {
        $arr = [];
        foreach ($collection as $item) {
            list($k, $v) = explode('|', $item);
            $arr[$k] = $v;
        } 
        return collect($arr);
    })->toArray()

];

Now config('sample.key') returns:

[
    "key1" => "value1",
    "key2" => "value2"
]
Sadegh19B's avatar

@158ltd Thanks for your solution.

Better Way for Readable in .env

# .env
MY_ENV_ARRAY="{'first_key': 'first', 'second_key': 'second', 'third_key': 'third'}"

# config/app.php (or create your own config file)
'my_env_array' => json_decode(str_replace("'", '"', env('MY_ENV_ARRAY')), true)
cosmorunner's avatar

You can use the Dotenv Class (comes with laravel) to load an .env-File to an array:

$envAsArray = Dotenv::createArrayBacked('/path/to/env-directory', '.env.example')->load();

MartinsCCS's avatar

in .env storing all my possible origin with coma. Exmpl : ORIGIN=test,test1,test2

config file to check request and validate it.

public function handle(Request $request, Closure $next) { $getOriginHeader = $request->header('Access-Control-Allow-Origin'); $getEnvHeaders = explode(',',env("ORIGIN"));

    foreach($getEnvHeaders as $singeOrigin) {
        if ($getOriginHeader == $singeOrigin) {
            $request->headers->set('Access-Control-Allow-Credentials', true);
            return $next($request);
        }
    }
    return response()->json([
        'data' => 'Wrong origin'
    ], 401);
}
hassaans2008's avatar

Using regex to extract all the variables could be an option!

Such as KEY_*

Please or to participate in this conversation.