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;
}
Answer: Use the PHP array_reverse() function You can use the PHP array_reverse() function to reverse the order of the array elements.
The array_reverse() function returns an array in the reverse order.
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.
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.
$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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With