Skip to content

Instantly share code, notes, and snippets.

@netojoaobatista
Last active December 29, 2015 00:09
Show Gist options
  • Save netojoaobatista/7584536 to your computer and use it in GitHub Desktop.
Save netojoaobatista/7584536 to your computer and use it in GitHub Desktop.
<?php
/**
* @see {@link http://docs.python.org/release/1.5.1p1/tut/range.html}
* @param integer start
* @param integer end
* @param integer step
* @return array
*/
function pyrange($start, $end = null, $step = null)
{
$range = array();
$step = $step?: 1;
$length = $start;
if (func_num_args() == 1) {
$start = 0;
} else {
$length = ceil(($end - $start)/$step);
}
for ($i = 0; $i < $length; ++$i, $start += $step) {
$range[] = $start;
}
return $range;
}
<?php
var_dump(pyrange(10));
/* output
array(10) {
[0] =>
int(0)
[1] =>
int(1)
[2] =>
int(2)
[3] =>
int(3)
[4] =>
int(4)
[5] =>
int(5)
[6] =>
int(6)
[7] =>
int(7)
[8] =>
int(8)
[9] =>
int(9)
}
*/
var_dump(pyrange(5, 10));
/*output
array(5) {
[0] =>
int(5)
[1] =>
int(6)
[2] =>
int(7)
[3] =>
int(8)
[4] =>
int(9)
}
*/
var_dump(pyrange(0, 10, 3));
/*output
array(4) {
[0] =>
int(0)
[1] =>
int(3)
[2] =>
int(6)
[3] =>
int(9)
}
*/
var_dump(pyrange(-10, -100, -30));
/*output
array(3) {
[0] =>
int(-10)
[1] =>
int(-40)
[2] =>
int(-70)
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment