PHP add / subtract letters

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, using $letter++ or $letter-- , I can move up or down a character. Is there a way to do something like $letter + 3 , so it adds 3 letters.

I know that I can create a function with a loop that adds char to char, and in the end I get the result. But is there a better way?

+4
source share
5 answers

There may 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); 

remember that after z

you will get other characters
+9
source

Try it...

  $letter = ord('A')+3; echo chr($letter); 
+2
source

Maybe this will work:

 $x = 'G'; $y = range('A','Z'); echo $y[array_search($x,$y)+3]; 
+1
source

Old thread, but in case someone is looking. Create an array of letters needed for writing, as in a spreadsheet.

 $alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M',..........'AY','AZ'); //add 36 to the letter A $val = (array_search('A',$alphabet)) + 36; echo $alphabet[$val]."<BR>"; 
0
source

I don't like any of these answers as they do not replicate the PHP function. Below is probably the easiest way to replicate it.

 function addLetters($letter,$lettersToAdd){ for ($i=0;$i<$lettersToAdd;$i++){ $letter++; } return $letter; } echo addLetters('G',4); echo "\n"; echo addLetters('Z',4); 

gives K AD

0
source

Source: https://habr.com/ru/post/1380539/


All Articles