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

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

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
1strncmp('aaa', 'aab', 2)0
2strncmp('aaa', 'aab', 3 )-1

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

export function strncmp(str1: string, str2: string, lgth: number): number {
// discuss at: https://locutus.io/php/strncmp/
// parity verified: PHP 8.3
// original by: Waldo Malqui Silva (https://waldo.malqui.info)
// input by: Steve Hilder
// improved by: Kevin van Zonneveld (https://kvz.io)
// revised by: gorthaur
// reimplemented by: Brett Zamir (https://brett-zamir.me)
// example 1: strncmp('aaa', 'aab', 2)
// returns 1: 0
// example 2: strncmp('aaa', 'aab', 3 )
// returns 2: -1

const s1 = (str1 + '').substr(0, lgth)
const s2 = (str2 + '').substr(0, lgth)

return s1 === s2 ? 0 : s1 > s2 ? 1 : -1
}

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