PHP's boolval 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 { boolval } from 'locutus/php/var/boolval'.

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

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
1boolval(true)true
2boolval(false)false
3boolval(0)false
4boolval(0.0)false
5boolval('')false
6boolval('0')false
7boolval([])false
8boolval('')false
9boolval(null)false
10boolval(undefined)false
11boolval('true')true

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

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

type BoolValue = PhpRuntimeValue

export function boolval(mixedVar: BoolValue): boolean {
// parity verified: PHP 8.3
// original by: Will Rowe
// example 1: boolval(true)
// returns 1: true
// example 2: boolval(false)
// returns 2: false
// example 3: boolval(0)
// returns 3: false
// example 4: boolval(0.0)
// returns 4: false
// example 5: boolval('')
// returns 5: false
// example 6: boolval('0')
// returns 6: false
// example 7: boolval([])
// returns 7: false
// example 8: boolval('')
// returns 8: false
// example 9: boolval(null)
// returns 9: false
// example 10: boolval(undefined)
// returns 10: false
// example 11: boolval('true')
// returns 11: true

if (mixedVar === false) {
return false
}

if (mixedVar === 0 || mixedVar === 0.0) {
return false
}

if (mixedVar === '' || mixedVar === '0') {
return false
}

if (Array.isArray(mixedVar) && mixedVar.length === 0) {
return false
}

if (mixedVar === null || mixedVar === undefined) {
return false
}

return true
}

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