I’m working on an array of numeric values.
I have a array of numeric values as the following in PHP
11,12,15,16,17,18,22,23,24
And I’m trying to convert it into range for e.g in above case it would be:
11-12,15-18,22-24
I don’t have any idea how to convert it into range.
I have used this one before, it does the trick.
Takes as input a comma separated string of numbers. Call to
sort
could be ignored if numbers are guaranteed to be sorted already.http://ideone.com/lmd7SY
This is my version folks. The algorithm is quite evident from the way I've coded it up, with comments at regular intervals. The approach was to divide the problem into sub-parts, and here's pseudo-code.
Pretty solid and hand coded in around 10 minutes.
Works for larger sets as well, tried and test:
You have to code it yourself ;-)
The algorithm is quite simple:
currentItem = prevItem + 1
then you haven't found a new range. Continue.The answer provided by Ali Gajani kept giving me "Illegal offset" warnings. So, because I figured somebody might want to use it as badly as I do, I'm posting my fixes here - though note that my fixes might be deemed silly by an advanced programmer - it does seem to work now with no issues.
I replaced/tweaked two parts of the code. Below you will see what I added (marked in bold) and what was removed, which I commented (//).
As near as I can tell, it was having trouble on the first pass because there was no "previous pass" to refer to (hence, it was balking at "$previous = $array[$i-1];") - and on the last pass for a similar reason. In that second instance, I simply moved "$next_key = $break_start[$i+1];" below the last iteration check.
If there are smarter ways to get this done, please advise. But I searched high and low for this - and figured someone else might also benefit. Another tip of the hat to Ali Gajani for his initial help.
You could do it like that:
Just adding my copy that is slightly different and supports a few extra things. I came here to compare it against other implementations. Here is test code to check the capability/correctness of my code:
The meat and potatoes, this is meant to be called statically within a class howver simply remove "static public" to use as a normal procedural function: