how to increment letters in php? [duplicate]

5

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

If the user types the letter B, it needs to transform it into a C-word.

    
asked by anonymous 04.07.2017 / 14:23

3 answers

7

In php it is only possible to use the increment operator ( ++ ) in letters (decrement -- does not apply) because it increments the ASCII code of the character the valid ranges are AZ 65-90, az 97 -122

You can generate the alphabet like this:

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

$letra = 'B';
echo ++$letra; //imprime C
    
04.07.2017 / 14:25
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"
    
04.07.2017 / 14:27
2

In an unorthodox way and XGH :

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

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

var_dump($proxima); // string(1) "D"
    
04.07.2017 / 14:46