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.
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.
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/
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 ;
}
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
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
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];
}
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.