Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP addition/subtraction of letters

Tags:

php

I have the following test code:

<?php

$letter = 'A';
$letter++;
$letter++;

echo $letter.'<br>';  // C

$letter++;
$letter++;
$letter++;

echo $letter.'<br>';  // F

// how to add plus 3 letters
// so that 
// $letter + 3 => I

As shown here by using $letter++ or $letter-- I can go up or down a character. Is there a way I can do something like $letter + 3 so it adds up 3 letters.

I know I can make a function with a loop which will add a char by char and at the end I will get the result. But is there a better way?

like image 755
Adnan Avatar asked Dec 17 '22 07:12

Adnan


1 Answers

There might be better solutions but the fastest way I can think of is:

  // get ASCII code of first letter
$ascii = ord('A');

  // echo letter for +3
echo chr($ascii + 3);

keep in mind that you will get other symbols after Z

like image 131
griessi Avatar answered Dec 18 '22 22:12

griessi