phpstringincrement

Increment a character by more than 1 step


Incrementing a character in php relative to its alphabetic position works as per:

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

The output is 'b'

However, is it possible to increment the position by multiples? i.e. 10 for example.

$a = 'a'; 
$a += 2;
echo $a;

This outputs an integer, not 'c'.


Solution

  • You can convert the character into its ASCII value using ord(), increment/decrement that value then convert it back to a character using chr():

    $a = 'a';
    $num = 2;
    $a = chr(ord($a)+$num);
    echo $a;
    // outputs c
    

    ord- Return ASCII value of character
    chr- Return a specific character

    If you want the increment/decrement to wrap around a value that exceeds z then you can use this:

    $a = 'a';
    $num = 28;
    echo chr((26 + (ord($a)+$num-97)) % 26 + 97);
    // outputs c
    

    Note: As php modulus of a negative number returns a negative number this will not work or $num values < -26 alternative solution include using gmp_mod as mentioned here.

    Hope this helps!