PHP's getenv in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { getenv } from 'locutus/php/info/getenv'.

Or with CommonJS: const { getenv } = require('locutus/php/info/getenv')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1getenv('LC_ALL')false

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to PHP's getenv looks like.

import { getPhpGlobalEntry, getPhpObjectEntry } from '../_helpers/_phpRuntimeState.ts'

export function getenv(varname: string): string | false {
// discuss at: https://locutus.io/php/getenv/
// parity verified: PHP 8.3
// original by: Brett Zamir (https://brett-zamir.me)
// example 1: getenv('LC_ALL')
// returns 1: false

const processValue = getPhpGlobalEntry('process')
const hasProcessLike = typeof processValue !== 'undefined'
if (hasProcessLike) {
return false
}

if (typeof processValue !== 'object' || processValue === null) {
return false
}

const envValue = getPhpObjectEntry(processValue, 'env')
if (typeof envValue !== 'object' || envValue === null) {
return false
}

const envEntry = getPhpObjectEntry(envValue, varname)
return typeof envEntry === 'string' && envEntry.length > 0 ? envEntry : false
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP info functions


Star