Skip to content

Add array_search_range() function - #23325

Open
sepehrphpr wants to merge 1 commit into
php:masterfrom
sepehrphpr:array_search_range
Open

Add array_search_range() function#23325
sepehrphpr wants to merge 1 commit into
php:masterfrom
sepehrphpr:array_search_range

Conversation

@sepehrphpr

Copy link
Copy Markdown

Add array_search_range() function

This PR adds a new array_search_range() function to the PHP standard library.
Function signature
array_search_range(mixed $needle, array $haystack, int $offset = 0, ?int $length = null, bool $strict = false): int|string|false
Description

array_search_range() searches a portion of the array for a given value and returns the first corresponding key if successful, or false if not found.

It extends the existing array_search() function with two additional parameters:

$offset — Start searching from this position (0-indexed). Negative values count from the end of the array.
$length — Limit the search to this many elements after $offset. If null, searches to the end of the array.

Examples
$array = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 2, 'e' => 1];

array_search_range(2, $array); // "b"
array_search_range(2, $array, 2); // "d"
array_search_range(2, $array, 0, 2); // "b"
array_search_range(1, $array, -2); // "e"

Comment thread ext/standard/array.c
max_count = length ? length : zend_hash_num_elements(ht);

ZEND_HASH_FOREACH_KEY_VAL_IND(ht, num_key, key_str, entry) {
if (i >= offset && (i < offset + max_count)) {

@IMSoP IMSoP Aug 18, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this is still going to iterate the whole array, and only the comparison is optimised. That's still going to be inefficient for very large arrays.

Completely ignoring the elements after the offset is trivial:

Suggested change
if (i >= offset && (i < offset + max_count)) {
if ( i < offset ) {
continue;
} elseif ( i >= offset + max_count ) {
break;
} else {

But if you look at the implementation of array_slice, it has extra optimisations for finding the start offset - some arrays are laid out sequentially in memory, so the memory address can be calculated without iterating.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants