How to write an array to an .env file using PHP

In this short guide, I will show you how to write a PHP function that takes an associative array of key-value pairs as a function parameter and writes its contents to a .env file.

Convert an PHP Array to .env file

The function has two parameters: the first is the path to the .env file, and the second is the associative array whose contents will be written to the file.

The function formats each key-value pair of the array into the "KEY=VALUE" format, typical of `.env` files.

function arrayToEnvFile($filePath, $array) {
  $content = '';

  foreach ($array as $key => $value) {
    // Ensure the key is a string and the value is scalar (not an array, object, etc.)
    if (!is_string($key) || !is_scalar($value)) {
      throw new InvalidArgumentException("Invalid key or value type.");

    // Escape if needed and format the line
    $key = strtoupper($key); // Optional: convert keys to uppercase
    $value = strval($value); // Convert the value to a string
    $value = strpos($value, ' ') !== false ? '"' . $value . '"' : $value; // Enclose the value in quotes if it contains spaces
    $content .= "{$key}={$value}\n";

  // Write to file
  if (file_put_contents($filePath, $content) === false) {
    throw new RuntimeException("Failed to write to the file at $filePath.");

// Example usage
$envFilePath = 'path/to/your/.env'; // Replace with the actual path to your .env file
$array = [
  'DB_HOST' => 'localhost',
  'DB_NAME' => 'example_db',
  'DB_USER' => 'user',
  'DB_PASS' => 'secret'

arrayToEnvFile($envFilePath, $array);

What does this PHP function do?

  • The $content string is built by iterating over the provided associative array.
  • Keys are converted to uppercase strings, which is a common convention in .env files (this is optional and can be adjusted as per your needs).
  • If a value contains spaces, it is enclosed in double quotes.
  • The resulting string is written to the file specified by $filePath. If the file doesn't exist, it will be created; if it does exist, it will be overwritten.

This function is a simple way to manage .env file contents programmatically. However, be cautious when handling sensitive data and ensure that the .env file is appropriately secured, especially in a production environment.

Leave a Comment