Created
November 25, 2011 04:06
-
-
Save felds/1392787 to your computer and use it in GitHub Desktop.
Creates an Excel column label from an integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment