Is it possible to get a range with PHP from A to ZZ*?
a b c ... aa ... zx zy zz
For me this didn\'t work:
range(\'A\', \'ZZ\');
You can combine two foreach loops to generate something like that.
// Single letters
foreach(range('A', 'Z') as $letter) {
echo $letter;
}
// AA-ZZ combinations
foreach(range('A', 'Z') as $letter1) {
foreach(range('A', 'Z') as $letter2) {
echo $letter1 . $letter2;
}
}
You could ofcourse write your own function to do this as it seems that the range() function in php doesn't support this. This should be an easy job, since you can just nest the range function in another loop. Something like this:
foreach(range('a', 'z') as $outer) {
foreach(range('a', 'z') as $inner) {
print($outer.$inner);
}
}
$atoz = range('A', 'Z');
$target = range('A', 'Z');
$result = $atoz;
foreach ($target as $val) {
$step = array_map(function ($elem) use ($val) {
return $val. $elem;
}, $atoz);
$result = array_merge($result, $step);
}
I use alpha2num() to convert alpha to number and then use it in loop. With this I can get the range using any value for the start and end.
// to convert alpha to number
function alpha2num($a) {
$l = strlen($a);
$n = 0;
for($i = 0; $i < $l; $i++)
$n = $n*26 + ord($a[$i]) - 0x40;
return $n-1;
}
// to convert number back to alpha
function num2alpha($n)
{
for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
$r = chr($n%26 + 0x41) . $r;
return $r;
}
function get_range($start_column, $end_column)
{
$s = alpha2num($start_column); // get start number
$e = alpha2num($end_column); // get end num
$columns = array();
// loop from start to end and change back the number to alpha to be stored in array
for($i=$s; $i<=$e; $i++)
$columns[] = num2alpha($i);
return $columns;
}
// usage
$columns = get_range('Z', 'BA'));
Even better option (Working great)
for ($i = 'a'; $i < 'zz'; $i++)
echo $i."<br>";
Take advantage of PHP's ability to increment characters "perl-style"
$letters = array();
$letter = 'A';
while ($letter !== 'AAA') {
$letters[] = $letter++;
}
But you could also use simple integer values, and take advantage of PHPExcel's built-in PHPExcel_Cell::stringFromColumnIndex() method
EDIT
From PHP 5.5, you can also use Generators to avoid actually building the array in memory
function excelColumnRange($lower, $upper) {
++$upper;
for ($i = $lower; $i !== $upper; ++$i) {
yield $i;
}
}
foreach (excelColumnRange('A', 'ZZ') as $value) {
echo $value, PHP_EOL;
}