<?php function array_search_range( mixed $needle, array $haystack, int $offset = 0, ?int $length = null, bool $strict = false, ): int|string|false { if ( $offset < 0 ) { $offset = count($haystack) + $offset; } if ( $length < 0 ) { $length = count($haystack) + $length - $offset; } $currentOffset = -1; foreach ( $haystack as $key => $value ) { $currentOffset++; if ( $currentOffset < $offset ) { continue; } if ( $length !== null && $currentOffset >= $offset + $length ) { break; } if ( ( $strict && $value === $needle ) || ( ! $strict && $value == $needle ) ) { return $key; } } return false; } $items = ['zero', 'one', 'two', 'target', 'four', 'target']; $key = array_search_range('target', $items, 2, 3, true); var_dump($key); // int(3) $items = ['zero', 'one', 'two', 'target', 'four', 'target']; $key = array_search_range('target', $items, 4, null, true); var_dump($key); // int(5) $items = ['zero', 'one', 'two', 'target', 'four', 'target']; $key = array_search_range('target', $items, 1, 2, true); var_dump($key); // bool(false) $items = ['zero', 'one', 'two', 'target', 'four', 'target']; $key = array_search_range('target', $items, 1, -3, true); var_dump($key); // bool(false)
You have javascript disabled. You will not be able to edit any code.