Skip to content

Instantly share code, notes, and snippets.

@Soben
Last active August 14, 2023 13:44
Show Gist options
  • Save Soben/8053bb0f03fd9a00b91b96de53fef0b8 to your computer and use it in GitHub Desktop.
Save Soben/8053bb0f03fd9a00b91b96de53fef0b8 to your computer and use it in GitHub Desktop.
Cassidoo | Sheet Column lookup to get true column number from letter structure.
<?php
/*
Solving Cassidoo's coding problem from the newsletter sent February 6th.
Co-Pilot assisted *sigh*
I was on track to solve the problem, but co-pilot immediately spurted out the `pow`
function before I had a chance to figure out the math. I'm not sure if I'm happy or
annoyed. Co-Pilot is also helping me type this message out :|
*/
function getColumnNames() {
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
function getLetterCount($letter) {
return (strpos(getColumnNames(), strtoupper($letter)) + 1);
}
function getBase($column) {
return pow(strlen(getColumnNames()), $column - 1);
}
function getColumnNumber($column) {
$columnLength = strlen($column);
$columnNumber = 0;
for ($i = 0; $i < $columnLength; $i++) {
$columnNumber += getLetterCount($column[$i]) * getBase($columnLength - $i);
}
return $columnNumber;
}
echo getColumnNumber("A") . PHP_EOL; // 1
echo getColumnNumber("AA") . PHP_EOL; // 27
echo getColumnNumber("AAZ") . PHP_EOL; // 728
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment