Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace OpenSpout\Writer\Common\Helper;
   6  
   7  /**
   8   * @internal
   9   */
  10  final class CellHelper
  11  {
  12      /** @var array<int, string> Cache containing the mapping column index => column letters */
  13      private static array $columnIndexToColumnLettersCache = [];
  14  
  15      /**
  16       * Returns the column letters (base 26) associated to the base 10 column index.
  17       * Excel uses A to Z letters for column indexing, where A is the 1st column,
  18       * Z is the 26th and AA is the 27th.
  19       * The mapping is zero based, so that 0 maps to A, B maps to 1, Z to 25 and AA to 26.
  20       *
  21       * @param int $columnIndexZeroBased The Excel column index (0, 42, ...)
  22       *
  23       * @return string The associated cell index ('A', 'BC', ...)
  24       */
  25      public static function getColumnLettersFromColumnIndex(int $columnIndexZeroBased): string
  26      {
  27          $originalColumnIndex = $columnIndexZeroBased;
  28  
  29          // Using isset here because it is way faster than array_key_exists...
  30          if (!isset(self::$columnIndexToColumnLettersCache[$originalColumnIndex])) {
  31              $columnLetters = '';
  32              $capitalAAsciiValue = \ord('A');
  33  
  34              do {
  35                  $modulus = $columnIndexZeroBased % 26;
  36                  $columnLetters = \chr($capitalAAsciiValue + $modulus).$columnLetters;
  37  
  38                  // substracting 1 because it's zero-based
  39                  $columnIndexZeroBased = (int) ($columnIndexZeroBased / 26) - 1;
  40              } while ($columnIndexZeroBased >= 0);
  41  
  42              self::$columnIndexToColumnLettersCache[$originalColumnIndex] = $columnLetters;
  43          }
  44  
  45          return self::$columnIndexToColumnLettersCache[$originalColumnIndex];
  46      }
  47  }