how to increment letters in php? [duplicate]
this question already has answers here :
increment letters in PHP?
(3 responses)
Closed there 3 years .
I need to make a program in php that increments a letter in the received name ex:
If the user enters precise letter B it turns it into a forward i.e. C.
5
3 answers
In php it is only possible to use the increment operator (++
) in letters (the decrement operator --
does not apply) because it increments the ASCII code of the character the valid ranges are A-Z 65-90, a-z 97-122
Can generate the alphabet like this:
$alfabeto = range('A', 'Z');
print_r($alfabeto);
$letra = 'B';
echo ++$letra; //imprime C
7
Author: rray, 2017-07-04 12:25:21
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"
5
Author: NilsonUehara, 2017-07-04 12:27:07
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"
2
Author: Marcelo de Andrade, 2017-07-04 12:46:02