tags:

views:

64

answers:

2

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"]
+2  A: 

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"
}
*/

?>
Austin Fitzpatrick
... or maybe it is a place for that.
webbiedave
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.
Austin Fitzpatrick
Thanks Austin, very kind of you to take the time I'll be sure to be less lazy with questions in future! thanks again
Haroldo
@Austin Fitzpatrick: Yeah, the code is so analogous it probably only took a minute.
webbiedave
A: 

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.

Felix Kling
ah ok, that makes sense now, thank you felix
Haroldo