PHP's array_rand in TypeScript

How to use

Install via yarn add locutus and import: import { array_rand } from 'locutus/php/array/array_rand'.

Or with CommonJS: const { array_rand } = require('locutus/php/array/array_rand')

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
1array_rand( ['Kevin'], 1 )'0'

PHP arrays and TypeScript/JavaScript

Please note that Locutus uses TypeScript/JavaScript objects as substitutes for PHP arrays, they are the closest we can get to this hashtable-like data structure without rolling our own. While many TypeScript/JavaScript implementations preserve the order of object properties, the ECMAScript Language Specification explicitly states that:

The mechanics and order of enumerating the properties is not specified.

In practice most engines preserve insertion order, but if your code depends on key ordering across platforms, keep this caveat in mind.

To influence how Locutus treats objects as arrays, you can check out the locutus.objectsAsArrays setting.

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

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

type RandomValue = PhpRuntimeValue

export function array_rand<TValue extends RandomValue>(array: PhpArrayLike<TValue>): string | null
export function array_rand<TValue extends RandomValue>(
array: PhpArrayLike<TValue>,
num: null | undefined,
): string | null
export function array_rand<TValue extends RandomValue>(array: PhpArrayLike<TValue>, num: 1): string | null
export function array_rand<TValue extends RandomValue>(
array: PhpArrayLike<TValue>,
num: number,
): string | string[] | null
export function array_rand<TValue extends RandomValue>(
array: PhpArrayLike<TValue>,
num?: number | null,
): string | string[] | null {
// discuss at: https://locutus.io/php/array_rand/
// original by: Waldo Malqui Silva (https://waldo.malqui.info)
// reimplemented by: Rafał Kukawski
// example 1: array_rand( ['Kevin'], 1 )
// returns 1: '0'

// By using Object.keys we support both, arrays and objects
// which phpjs wants to support
const keys = Object.keys(array)

if (typeof num === 'undefined' || num === null) {
num = 1
} else {
num = +num
}

if (isNaN(num) || num < 1 || num > keys.length) {
return null
}

// shuffle the array of keys
for (let i = keys.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)) // 0 ≤ j ≤ i

const tmp = keys[j]
const current = keys[i]
if (tmp === undefined || current === undefined) {
return null
}
keys[j] = current
keys[i] = tmp
}

return num === 1 ? (keys[0] ?? null) : keys.slice(0, num)
}

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


Star