PHP's implode in TypeScript

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

How to use

Install via yarn add locutus and import: import { implode } from 'locutus/php/strings/implode'.

Or with CommonJS: const { implode } = require('locutus/php/strings/implode')

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
1implode(' ', ['Kevin', 'van', 'Zonneveld'])'Kevin van Zonneveld'
2implode(' ', {first:'Kevin', last: 'van Zonneveld'})'Kevin van Zonneveld'

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

import type { PhpAssoc, PhpRuntimeValue } from '../_helpers/_phpTypes.ts'

type ImplodeValue = PhpRuntimeValue
type KeyedValues = PhpAssoc<ImplodeValue>

export function implode(pieces: ImplodeValue[] | KeyedValues | string | undefined): string

export function implode(glue: string, pieces: ImplodeValue[] | KeyedValues | string | undefined): string

export function implode(
...providedArgs: [
glueOrPieces?: ImplodeValue[] | KeyedValues | string,
pieces?: ImplodeValue[] | KeyedValues | string | undefined,
]
): string {
// discuss at: https://locutus.io/php/implode/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// improved by: Waldo Malqui Silva (https://waldo.malqui.info)
// improved by: Itsacon (https://www.itsacon.net/)
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// example 1: implode(' ', ['Kevin', 'van', 'Zonneveld'])
// returns 1: 'Kevin van Zonneveld'
// example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'})
// returns 2: 'Kevin van Zonneveld'

let retVal = ''
let tGlue = ''
let actualGlue = ''
let actualPieces: ImplodeValue[] | KeyedValues | string | undefined

if (providedArgs.length === 1) {
const [glueOrPieces] = providedArgs
actualPieces = glueOrPieces
} else {
const [glueOrPieces, pieces] = providedArgs
actualGlue = String(glueOrPieces ?? '')
actualPieces = pieces
}

if (typeof actualPieces === 'object' && actualPieces !== null) {
if (Array.isArray(actualPieces)) {
return actualPieces.join(actualGlue)
}
for (const key in actualPieces) {
retVal += tGlue + actualPieces[key]
tGlue = actualGlue
}
return retVal
}

return String(actualPieces)
}

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 strings functions


Star