Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment letters like numbers in PHP?

Tags:

php

I would like to write a function that takes in 3 characters and increments it and returns the newly incremented characters as a string.

I know how to increase a single letter to the next one but how would I know when to increase the second letters and then stop and then increase the first letter again to have a sequential increase?

So if AAA is passed, return AAB. If AAZ is passed return ABA (hard part).

I would appreciate help with the logic and what php functions will be useful to use.

Even better, has some done this already or there is a class available to do this??

Thanks all for any help

like image 581
Abs Avatar asked Aug 25 '10 14:08

Abs


People also ask

How to increment letters in php?

PHP has a built-in way of incrementing either a number or a string simply by placing ++ at the end of the variable. echo $i; But you can also do this for letters; PHP will increment the variable to the next letter in the alphabet.

How do you increment a character in JavaScript?

Use the String. fromCharCode() method to increment a letter in JavaScript, e.g. String. fromCharCode(char. charCodeAt(0) + 1) .


2 Answers

Character/string increment works in PHP (though decrement doesn't)

$x = 'AAZ'; $x++; echo $x;  // 'ABA' 
like image 148
Mark Baker Avatar answered Sep 18 '22 13:09

Mark Baker


You can do it with the ++ operator.

$i = 'aaz'; $i++; print $i; 

aba

However this implementation has some strange things:

for($i = 'a'; $i < 'z'; $i++) print "$i "; 

This will print out letters from a to y.

for($i = 'a'; $i <= 'z'; $i++) print "$i "; 

This will print out lettes from a to z and it continues with aa and ends with yz.

like image 34
tamasd Avatar answered Sep 18 '22 13:09

tamasd