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 itterate if the $end_column was already set in a previous itteration.
// 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;
}
2
Answers
For what you are looking you will have to 2 arrays for letters and 1 for the numbers.
Because you want a letter alone before moving to the AA AB etc. We have to run the first array with only a letter.
Hope this can help.
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.