2

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

6 Answers6

4

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/

Averias
  • 931
  • 1
  • 11
  • 20
3

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 ;
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
1

You can compare and increment strings the exact same way as numbers, just change the initialisation and exit conditions of the loop:

for($i='A'; $i<='C'; $i++) {
  echo $i, PHP_EOL;
}

A
B
C

See https://eval.in/974692

iainn
  • 16,826
  • 9
  • 33
  • 40
1

One option is to use range and use foreach to loop.

$letters = range("A","C");
foreach( $letters as $letter ) {
    echo $letter . "<br />";
}

This will result to:

A
B
C
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

You could just create an array of letters like so, and use the index of the forloop to loop through them.

$letters = array('a','b','c');

    for($i=0;$i<=2;$i++)
    {
        echo  $letters[$i];
    }
Juakali92
  • 1,155
  • 8
  • 20
0

Similar to above, you could set a variable to $x = "abcdefg..." and echo substr($x, $i, 1). You will need to reset $i to 1 whenever it reaches 27.

Old Guy
  • 31
  • 4