My javascript isnt so great, but i found a brilliant looking function here
I'm not sure what to do with this bit:
var ranges = [], rstart, rend;
full function:
function getRanges(array) {
var ranges = [], rstart, rend;
for (var i = 0; i < array.length; i++) {
rstart = array[i];
rend = rstart;
while (array[i + 1] - array[i] == 1) {
rend = array[i + 1]; // increment the index if the numbers sequential
i++;
}
ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);
}
return ranges;
}
getRanges([2,3,4,5,10,18,19,20]);
// returns ["2-5", "10", "18-20"]
getRanges([1,2,3,5,7,9,10,11,12,14 ]);
// returns ["1-3", "5", "7", "9-12", "14"]
getRanges([1,2,3,4,5,6,7,8,9,10])
// returns ["1-10"]
asked Apr 19, 2010 at 15:31
Haroldo
37.5k48 gold badges131 silver badges169 bronze badges
2 Answers 2
It's almost exactly the same in PHP.
<?php
function getRanges($array){
$ranges = array();
for($i = 0; $i < count($array); $i++){
$rstart = $array[$i];
$rend = $rstart;
while($array[$i + 1] - $array[$i] == 1){
$rend = $array[$i + 1]; //incremenent the index if sequential
$i++;
}
$ranges[] = ($rstart == $rend) ? $rstart.'' : $rstart . '-' . $rend;
}
return $ranges;
}
var_dump(getRanges(array(2,3,4,5,10,18,19,20)));
/*
array(3) {
[0]=>
string(3) "2-5"
[1]=>
string(2) "10"
[2]=>
string(5) "18-20"
}
*/
?>
answered Apr 19, 2010 at 15:41
Austin Fitzpatrick
7,3693 gold badges28 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
webbiedave
... or maybe it is a place for that.
Austin Fitzpatrick
Yeah, I thought about not answering but sometimes it helps to have someone spell it out for you a couple times when you're new. It wasn't much "work" for me, find and replace the variable names with a "$" infront and replace "+" with "." in a few places.
Haroldo
Thanks Austin, very kind of you to take the time I'll be sure to be less lazy with questions in future! thanks again
webbiedave
Yeah, the code is so analogous it probably only took a minute.
Just for your information:
var ranges = [], rstart, rend;
just declares three variables ranges, rstart and rend. ranges is also initialized as an empty array.
It is the same as
var ranges = [];
var rstart;
var rend;
In PHP you don't necessarily have to declare the variables beforehand.
answered Apr 19, 2010 at 15:47
Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
Comments
default
$, array initialization isarray(),array.lengthtranslates tocount($array),array.pushis either$array[]=orarray_push($array, $value)and concatenation goes with.instead of+.$ranges=array();- you don't have to define beginning and end of an array in php.