joshdcomp
joshdcomp

Reputation: 1678

Increment list in PHP alphabetically

I'm working on something where the user is generating a number of objects in a form. When they submit the form, I want to echo the results back to them in a list (very distilled summary of what I'm doing).

In PHP, I know how to increment something in the conventional manner (1, 2, 3), but due to elements in the UI, I want to increment the list alphabetically (A, B, C). How would I do this?

Working code incrementing the list numerically:

//LOOP THROUGH THE ARRAY OF OBJECTS PASSED TO THIS PAGE FROM THE FORM
foreach ($waypoints as $key => $value) {
$current = $key + 1;
    echo "<p><strong>Waypoint #$current:</strong> $value</p>";
}

Upvotes: 1

Views: 3977

Answers (4)

rk3263025
rk3263025

Reputation: 71

You can increment alphabetically using this code

 echo $letter = 'A';
 for($i= 1; $i <=25 ;$i++)
     {
     $letter++;
     echo     $letter;
     }

Upvotes: 2

TheImpact
TheImpact

Reputation: 191

Functions ord & chr should help you.

ord('A') will give you the ASCII value of 'A'

char(X) will give you the character for ASCII value X

print chr(ord('A')+1); // outputs B

Upvotes: 1

Phil
Phil

Reputation: 164913

You could do something like

$current = chr($key + 65);

Of course, you'd have to work out what happens when $key reaches 26.

Upvotes: 1

zerkms
zerkms

Reputation: 255005

You can increment letters in the same way:

$letter = 'A';
$letter++;

echo $letter;

Upvotes: 12

Related Questions