Automattic\WooCommerce\Utilities

ArrayUtil::to_ranges_string()public staticWC 1.0

Converts an array of numbers to a human-readable range, such as "1,2,3,5" to "1-3, 5". It also supports floating point numbers, however with some perhaps unexpected / undefined behaviour if used within a range. Source: https://stackoverflow.com/a/34254663/4574

Method of the class: ArrayUtil{}

No Hooks.

Return

String.

Usage

$result = ArrayUtil::to_ranges_string( $items, $item_separator, $range_separator, $sort ): string;
$items(array) (required)
An array (in any order, see $sort) of individual numbers.
$item_separator(string)
The string that separates sequential range groups.
Default: ', '
$range_separator(string)
The string that separates ranges. A plausible example otherwise would be ' to '.
Default: '-'
$sort(true|false|true)
Sort the array prior to iterating? You'll likely always want to sort, but if not, you can set this to false.
Default: true

ArrayUtil::to_ranges_string() code WC 9.4.2

public static function to_ranges_string( array $items, string $item_separator = ', ', string $range_separator = '-', bool $sort = true ): string {
	if ( $sort ) {
		sort( $items );
	}

	$point = null;
	$range = false;
	$str   = '';

	foreach ( $items as $i ) {
		if ( null === $point ) {
			$str .= $i;
		} elseif ( ( $point + 1 ) === $i ) {
			$range = true;
		} else {
			if ( $range ) {
				$str  .= $range_separator . $point;
				$range = false;
			}
			$str .= $item_separator . $i;
		}
		$point = $i;
	}

	if ( $range ) {
		$str .= $range_separator . $point;
	}

	return $str;
}