
Generating an alphabetical list from A to Z in PHP is a common requirement for various applications. Whether you want the output as A1, B1, C1... or simply A, B, C..., PHP offers multiple ways to achieve this. Here's a step-by-step guide.
Method 1: Using range() Function
PHP's range() function allows you to create an array of characters from A to Z.
Option 1: With a Suffix Like 1
foreach (range('A', 'Z') as $letter) {
echo $letter . '1' . PHP_EOL; // Output: A1, B1, C1...
}
Option 2: Without Any Suffix
foreach (range('A', 'Z') as $letter) {
echo $letter . PHP_EOL; // Output: A, B, C...
}
Method 2: Using ASCII Values
You can loop through the ASCII values of uppercase letters (65-90):
for ($i = 65; $i <= 90; $i++) {
echo chr($i) . '1' . PHP_EOL; // With 1 as a suffix
// echo chr($i) . PHP_EOL; // Without 1
}
Method 3: Using a for Loop with range()
$alphabet = range('A', 'Z');
for ($i = 0; $i < count($alphabet); $i++) {
echo $alphabet[$i] . '1' . PHP_EOL; // With 1
// echo $alphabet[$i] . PHP_EOL; // Without 1
}
Output Examples
With 1
A1
B1
C1
...
Without 1
A
B
C
...
Conclusion
Using these simple PHP techniques, you can easily generate an alphabetical list from A to Z, with or without a suffix. Choose the method that best fits your project's requirements.