Last active
November 22, 2018 11:08
-
-
Save Vince0789/f6aef5b445470fea52049baa56fb6eb0 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Converts a column name into the corresponding index (A = 0, B = 1, AA = 26, etc). | |
* | |
* @param string $name | |
* @return int | |
*/ | |
function getColumnIndexFromName($name) | |
{ | |
$chars = array_map(function($char) { return ord($char); }, str_split(strtoupper($name))); | |
$index = 0; | |
$pow = 1; | |
for($i = count($chars) - 1; $i >= 0; $i--) | |
{ | |
$index += (($chars[$i] - ord('A') + 1) * $pow); | |
$pow *= 26; | |
} | |
return $index - 1; | |
} | |
/** | |
* Converts a column index to the corresponding name (0 = A, 1 = B, 26 = AA, etc). | |
* | |
* @param int $index | |
* @return string | |
* @throws OutOfRangeException | |
*/ | |
function getColumnNameFromIndex($index) | |
{ | |
if($index < 0) | |
throw new OutOfRangeException(); | |
$chars = array(); | |
while($index >= 0) | |
{ | |
$chars[] = chr(ord('A') + ($index % 26)); | |
$index = intdiv($index, 26) - 1; | |
} | |
return implode('', array_reverse($chars)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment