PHP's strval in TypeScript

How to use

Install via yarn add locutus and import: import { strval } from 'locutus/php/var/strval'.

Or with CommonJS: const { strval } = require('locutus/php/var/strval')

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
1strval({red: 1, green: 2, blue: 3, white: 4})'Object'

Dependencies

This function uses the following Locutus functions:

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

import type { PhpRuntimeValue } from '../_helpers/_phpTypes.ts'
import { gettype } from '../var/gettype.ts'

type StringValue = PhpRuntimeValue

export function strval(str: StringValue): string {
// discuss at: https://locutus.io/php/strval/
// original by: Brett Zamir (https://brett-zamir.me)
// improved by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// example 1: strval({red: 1, green: 2, blue: 3, white: 4})
// returns 1: 'Object'

let type = ''

if (str === null) {
return ''
}

type = gettype(str)

// Comment out the entire switch if you want JS-like
// behavior instead of PHP behavior
switch (type) {
case 'boolean':
if (str === true) {
return '1'
}
return ''
case 'array':
return 'Array'
case 'object':
return 'Object'
}

return String(str)
}

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


Star