November 20, 2016 —John Koster
env($key, $default = null)
The env
function can be used to get an environment variables value. If an environment value with the given $key
exists, its value will be returned. If the given $key
does not exist, the $default
value will be returned instead, which is null
by default. The following examples will show examples of the env
function.
The following examples will use the following .env
file:
1APP_ENV=local 2APP_DEBUG=true 3APP_KEY=SomeRandomString 4 5DB_HOST=localhost 6DB_DATABASE=homestead 7DB_USERNAME=homestead 8DB_PASSWORD=secret 910CACHE_DRIVER=file11SESSION_DRIVER=file1213TEST_TRUE1=true14TEST_TRUE2=(true)1516TEST_FALSE1=false17TEST_FALSE2=(false)1819TEST_NULL1=null20TEST_NULL2=(null)2122TEST_EMPTY1=empty23TEST_EMPTY2=(empty)
The returned value will appear above the function call as a comment (the actual values returned will likely be different based on application specifics and environment configuration):
1<?php 2 3// local 4env('APP_ENV'); 5 6// true 7env('APP_DEBUG'); 8 9// A rather long default value10env('NonExistent', 'A rather long default value');
The env
function will automatically convert boolean string representations and null representations into their corresponding PHP value. In the above example configuration file, the values returned for TEST_TRUE1
, TEST_TRUE2
, TEST_FALSE1
and TEST_FALSE2
will automatically be converted to a boolean type. The values returned for TEST_NULL1
and TEST_NULL2
will automatically be converted to a null
type. The values returned for TEST_EMPTY1
and TEST_EMPTY2
will actually be an empty string, with a length of 0
.
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.