Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-increment for alphabet using PHP [duplicate]

Tags:

php

for-loop

I am trying auto-increment using PHP to generate English alphabets instead numbers. I know how to do auto increment for numbers:

for ($i = 0; $i <= 2; $i++) {
    echo $i;
}

But I want a way I can generate ABC instead 123.

like image 588
SimulationCode Avatar asked Jul 25 '26 01:07

SimulationCode


2 Answers

You can use chr function together with ASCII code to generate them

For UpperCase:

for ($i = 65; $i <= 90; $i++) {
    echo chr($i) . PHP_EOL;
}

For LowerCase:

for ($i = 97; $i <= 122; $i++) {
    echo chr($i) . PHP_EOL;
}

Here the complete list of ASCII codes: https://www.ascii-code.com/

like image 189
Averias Avatar answered Jul 27 '26 15:07

Averias


Just get the ascii code for A and loop for 26

<?php
$a_is = ord('A');

for ( $ch=$a_is; $ch<$a_is+26; $ch++ ) {
    echo chr($ch) . PHP_EOL ;
}

Or set a char count

<?php
$a_is = ord('A');
$stop = 5;

for ( $ch=$a_is; $ch<$a_is+$stop; $ch++ ) {
    echo chr($ch) . PHP_EOL ;
}
like image 30
RiggsFolly Avatar answered Jul 27 '26 15:07

RiggsFolly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!