Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Hello,
I have a little function that I wrote to convert an array of numbers (array(1,2,3,5,7,8,9)) to a string range (1-3,5,7-9) similar to what is used by the crontab. What i wanted is to see if anyone has a better version for this or any optimizations to my code that could be made.Code: Select all
<?php
function array_to_range($arr) {
$result = array();
$v1 = $v2 = $arr[0];
for ($i = 1; $i < count($arr); $i++) {
if ($arr[$i] == ($v2 + 1)) {
$v2 = $arr[$i];
} else {
$result[] = ($v2 > $v1) ? $v1 . '-' . $v2 : $v2;
$v1 = $v2 = $arr[$i];
}
}
$result[] = ($v2 > $v1) ? $v1 . '-' . $v2 : $v2;
return implode(',', $result);
}
$array = array(
1,2,3,5,6,7,9
);
# prints '1-3,5-7,9'
echo array_to_range($array);
?>feyd | Please use
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]