Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse range-like functionality in php arrays


I have an array like this:

array(0, 2, 4, 5, 6, 7, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99);

and I want to get it as a the following string:

0, 2, 4-7, 90+

Any examples out there before I start to pull hairs from my head ?
Thanks.

UPDATE:
Here is the final solution I used after taking @Andy's code, and modifying it a bit.

function rangeArrayToString($rangeArray, $max = 99) {
    sort($rangeArray);
    $first = $last = null;
    $output = array();

    foreach ($rangeArray as $item) {
        if ($first === null) {
            $first = $last = $item;
        } else if ($last < $item - 1) {
            $output[] = $first == $last ? $first : $first . '-' . $last;
            $first = $last = $item;
        } else {
            $last = $item;
        }
    }

    $finalAddition = $first;

    if ($first != $last) {
        if ($last == $max) {
            $finalAddition .= '+';
        } else {
            $finalAddition .= '-' . $last;
        }
    }

    $output[] = $finalAddition;

    $output = implode(', ', $output);
    return $output;
}
like image 967
Doron Avatar asked Dec 23 '10 14:12

Doron


People also ask

How do I reverse an array in PHP?

Answer: Use the PHP array_reverse() function You can use the PHP array_reverse() function to reverse the order of the array elements.

Which function is used to get an array in the reverse order?

The array_reverse() function returns an array in the reverse order.

What is Range function PHP?

The range() function creates an array containing a range of elements. This function returns an array of elements from low to high. Note: If the low parameter is higher than the high parameter, the range array will be from high to low.

What does => mean in PHP array?

It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.


1 Answers

$first = $last = null;
$output = array();

foreach ($array as $item) {
    if ($first === null) {
        $first = $last = $item;
    } else if ($last < $item - 1) {
        $output[] = $first == $last ? $first : $first . '-' . $last;
        $first = $last = $item;
    } else {
        $last = $item;
    }
}

$output[] = $first == $last ? $first : $first . '+';
$output = join(', ', $output);
like image 145
Andy Avatar answered Oct 18 '22 03:10

Andy