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

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

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
1var $transport = ['foot', 'bike', 'car', 'plane'] next($transport) next($transport)'car'

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.

Notes

  • Uses global: locutus to store the array pointer

Dependencies

This function uses the following Locutus functions:

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

import { getEntryAtCursor, getPointerState } from '../_helpers/_arrayPointers.ts'
import type { PhpArrayLike } from '../_helpers/_phpTypes.ts'

export function next<T>(arr: PhpArrayLike<T>): T | false {
// discuss at: https://locutus.io/php/next/
// parity verified: PHP 8.3
// original by: Brett Zamir (https://brett-zamir.me)
// note 1: Uses global: locutus to store the array pointer
// example 1: var $transport = ['foot', 'bike', 'car', 'plane']
// example 1: next($transport)
// example 1: next($transport)
// returns 1: 'car'

const state = getPointerState(arr, true)
if (!state) {
return false
}

const nextCursor = state.cursor + 1
const entry = getEntryAtCursor(arr, nextCursor)
if (!entry) {
return false
}

state.setCursor(nextCursor)
return entry[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 array functions


Star