![]() |
Generating a Range of Numbers the Easy Way
After Haris' mention of the PHP function
range(), I thought the kindest thing to do would be to give it a proper introduction. So here is that introduction!Range is native PHP function that takes 2 compulsory arguments and 1 optional argument (As of PHP 5.0.0 which defaults to 1) and returns an array. Seem ever so simple? Well it is! The 3 arguments the function can accept are as follows:
Take the example below which will begin at 0, increment in steps of 10 until we get to 50. PHP Code:
0 10 20 30 40 50 being returned. If you were to assign the result of the range() into an array then all you would see is a nicely constructed array:Code:
Arrayrange():PHP Code:
A, B, C, D, E, F. Range can also go backwards, which can be a whole lot of fun. Not quite as exciting as a rollercoaster going backwards but I hope you appreciate me trying to liven the article up!PHP Code:
100, 75, 50, 25, 0!There is not a lot more to it. Such an easy function but one that is perhaps not as well heard of as it should be. I can't say that I've really needed this function before, however, perhaps there might be an occasion where you would require its presence! I'd be interested to know if anyone out there has any really good uses for it? I've seen some good uses on php.net for such tasks as checking if an array is associative - but any more would be great to hear! |
Good article/introduction.
What's the advantage of using range() instead of just a for loop? |
Range creates an array of the numbers without and has less overhead than calling a loop. It's basically quicker, but if you're planning on printing the numbers, than it's better to use a for loop, because you'll eventually have to loop the range array to print it out.
|
I must admit that I've never used the range function, despite being fully aware of it. I suppose the only instance I could think of using it, is in an array:
php Code:
What other purposes are there? |
Quote:
|
It has it's uses. I've populated arrays with A-Z using range. Easier than typing out every letter.
|
| All times are GMT. The time now is 07:47 AM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0