how to increment letters in php?

Asked

Viewed 860 times

5

I need to make a script in php that increments a letter in the received name ex:

if the user type B letter need to transform it into a forward or C.

  • 1

    you can create an array with all the letters of the alphabet, when the user type the letter, find the letter in the array and pick the next index.

3 answers

7


In php you can only use the increment operator (++) in letters (the decreasing -- does not apply) as it increments the character ASCII code the valid ranges are A-Z 65-90, a-z 97-122

You can generate the alphabet that way:

$alfabeto = range('A', 'Z');
print_r($alfabeto); 

$letra = 'B';
echo ++$letra; //imprime C

5

You can convert the character to ASCII, increment +1 and convert it back to character:

echo ord("B"); //retorna 66
echo chr(ord("B")+1); //retorna "C"

2

In an unorthodox and XGH:

$letra = 'C';
$alfabeto = range('A', 'Z');

$proxima = $alfabeto[array_search($letra, $alfabeto) +1]; 

var_dump($proxima); // string(1) "D"
  • 1

    It would be interesting to note that by doing the rest of the division by the size of the list, $alfabeto[(array_search($letra, $alfabeto)+1) % count($alfabeto)], the letter Z is converted into A, assuming this is the desired behavior (it is not clear in the question).

  • Yes yes, @Andersoncarloswoss. As it is not really clear how the result is desired if it is the letter Z, I didn’t mention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.