note 45913 added to function.range

From: Date: Thu, 23 Sep 2004 11:23:43 +0000
Subject: note 45913 added to function.range
Groups: php.notes 
Request: Send a blank email to php-notes+get-77239@lists.php.net to get a copy of this message
i figured i'd add some more functionality to the myRange() functions below. now you can, besides giving a $step parameter, 1. count backwards 2. count with letters 3. give whatever parameter you want, there's nothing (i know of) that will cause an endless loop (try a negative $step for the previous function....) <?php function myRange($num1, $num2, $step=1) { if (is_numeric($num1) && is_numeric($num2)) { //we have a numeric range $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive $dir = ($num1<=$num2 ? 1 : -1); //get the direction for($i = (float)$num1; $i*$dir <= $num2*$dir; $i += $step*$dir) { $temp[] = $i; } } else { //we have a character range $num1=ord((string)$num1); //convert to ascii value $num2=ord((string)$num2); $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive $dir = ($num1<=$num2 ? 1 : -1); //get direction for($i = $num1; $i*$dir <= $num2*$dir; $i += $step*$dir) { $temp[] = chr($i); } } return $temp; } print_r(myRange( 1, 3, 0.5 )); //you can use fractional steps print_r(myRange( "a", "k", 3 )); //or count letters print_r(myRange( "5", "9" )); //numbers are detected even if hidden in strtings print_r(myRange( "!", "%", 1/pi() )); //or mess around with senseless parameters ?> ---- Manual Page -- http://www.php.net/manual/en/function.range.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45913 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45913&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45913&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#77239) next »