Search code examples
phpexcelloopsletter

PHP -Iterate letters in PHP with a custom format


I need to iterate letters in PHP in the following order. A, AA, AB, AC-AZ, B,BA,BB,BC,BD...BZ..

What I have right now is like the Excel columns from a-z, then aa,ab,ac. I'm currently struggling the find a logical way to do the requirement.

Please note that I need to exhaust the range 1 to 200 before i transition to aa.

For example

1a
2a
3a

up to

200a
1aa
2aa
3aa

up to

200aa
1ab

Here's the code I'm using:

public function createColumnsArray($end_column, $first_letters = '')
{
    $columns = array();
    $length = strlen($end_column);
    $letters = range('A', 'Z');

    // Iterate over 26 letters.
    foreach ($letters as $letter) {
        // Paste the $first_letters before the next.
        $column = $first_letters . $letter;

        // Add the column to the final array.
        $columns[] = $column;

        // If it was the end column that was added, return the columns.
        if ($column == $end_column)
            return $columns;
    }

    // Add the column children.
    foreach ($columns as $column) {
        // Don't iterate if the $end_column was already set in a previous iteration.
        // Stop iterating if you've reached the maximum character length.
        if (!in_array($end_column, $columns) && strlen($column) < $length) {
            $new_columns = $this->createColumnsArray($end_column, $column);
            // Merge the new columns which were created with the final columns array.
            $columns = array_merge($columns, $new_columns);
        }
    }

    return $columns;
}

Solution

  • $letters1 = range('A', 'Z');
    $letters2 = array_merge([''], range('A', 'Z'));
    
    foreach($letters1 as $l1) {
        foreach($letters2 as $l2) {
            for($i=1; $i<=200; ++$i) {
                $result[] = $i.$l1.$l2;
            }
        }
    }
    print_r($result);
    

    The "trick" I am using here is to put an empty string into the second "letter" array. That way, we can just use nested loops, and concatenate three parts - the number, the first letter, and the second letter - every time, without having to treat the values that consist only of number and one letter, any differently.