Skip to content

Instantly share code, notes, and snippets.

@felds
Created November 25, 2011 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felds/1392787 to your computer and use it in GitHub Desktop.
Save felds/1392787 to your computer and use it in GitHub Desktop.
Creates an Excel column label from an integer
<?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