public
Created

Creates an Excel column label from an integer

  • Download Gist
column_label.function.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
<?php
 
/**
* Creates an Excel column label from an integer where 0 = A,
* 25 = Z, 26 = AA and so on.
*
* Examples:
* <code>
* <?php
* echo column_label(0); // A
* echo column_label(25); // Z
* echo column_label(26); // AA
* echo column_label(702); // AAA
* ?>
* </code>
*
* @author Felds Liscia <dev@felds.com.br>
* @param integer $pos The column index
* @return string The label
*/
function column_label($pos)
{
// normalizes the input
$pos = (int) $pos;
 
// generating an array of letters like [A, B, C, ..Z]
static $letters;
if (! $letters) $letters = range('A', 'Z');
 
// if the column index is equal or larger than 26 (# of letters from A~Z) ...
if ($pos >= count($letters)) {
// ... it returns the integer division product by the same process
// followed by the remainder of the division
return column_label(floor($pos / count($letters))-1) . column_label($pos % count($letters));
} else {
// otherwise, it just picks a index from the range
return $letters[$pos];
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.