PHP 8.5.0 Released!

Voting

: four minus three?
(Example: nine)

The Note You're Voting On

luca.favorido ATgmailDOT com
9 years ago
The function "range" is very useful to get an array of characters as range('C','R') does.
At work, I had to extend the function range($a,$b) to work in this special case: with two uppercase strings $a and $b, it should return all the possible strings between $a and $b.
This could be used for example to get the excel column indexes.
e.g. <?php range('A','AD') ==> array('A','B','C',...,'Z','AA','AB','AC','AD') ?>

So I wrote the function getrange($min,$max) that exactly does this.
<?php
function getcolumnrange($min,$max){
 $pointer=strtoupper($min);
 $output=array();
 while(positionalcomparison($pointer,strtoupper($max))<=0){
 array_push($output,$pointer);
 $pointer++;
 }
 return $output;
}
function positionalcomparison($a,$b){
 $a1=stringtointvalue($a); $b1=stringtointvalue($b);
 if($a1>$b1)return 1;
 else if($a1<$b1)return -1;
 else return 0;
}
/*
* e.g. A=1 - B=2 - Z=26 - AA=27 - CZ=104 - DA=105 - ZZ=702 - AAA=703
*/
function stringtointvalue($str){
 $amount=0;
 $strarra=array_reverse(str_split($str));
 for($i=0;$i<strlen($str);$i++){
 $amount+=(ord($strarra[$i])-64)*pow(26,$i);
 }
 return $amount;
}
?>

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /