Skip to content

Instantly share code, notes, and snippets.

@Vince0789
Last active November 22, 2018 11:08
Show Gist options
  • Save Vince0789/f6aef5b445470fea52049baa56fb6eb0 to your computer and use it in GitHub Desktop.
Save Vince0789/f6aef5b445470fea52049baa56fb6eb0 to your computer and use it in GitHub Desktop.
<?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