Skip to content

How to increment letters like numbers in PHP?

In PHP, you can use the ++ operator to increment a single-character string, or use ord() and chr() to add a specific number to a letter. Here's an example:

Example of using the ++ operator to increment a letter in PHP

php
<?php

$letter = 'a';
$letter++;
echo $letter;

This will output "b".

The += operator does not work for incrementing letters because PHP converts non-numeric strings to 0 for arithmetic operations. To add a specific number to a letter, you need to convert the string to its ASCII code, perform the arithmetic operation, and then convert the result back to a string.

Example of adding a number to a letter using ord() and chr() in PHP

php
<?php

$letter = 'a';
$letter = chr(ord($letter) + 3);
echo $letter;

This will output "d".

Note that the ++ operator simply increments the ASCII value of the character. It does not wrap around at 'z' or 'Z'; for example, incrementing 'z' results in '{' (ASCII 123).

Dual-run preview — compare with live Symfony routes.