1

I want to increment a letter by 2 each time, e.g.

// increment by 1
$alphabet = "A";
$alphabet++; // 'B'

I want something like

// increment by 2
$alphabet = "A";
$alphabet+=2; // 'C'

How can i do this? I tried the code above but encounter non numeric value.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
Crazy
  • 847
  • 1
  • 18
  • 41
  • 1
    There is no magic "addition" of characters, just multiple-increments.... if you want that, then create a `function incrementor(&$characters, $counter) { do $characters++; } while($counter-- > 0); }`, calling it like `incrementor($alphabet, 2);` – Mark Baker Nov 24 '17 at 17:03
  • @MarkBaker Do you mean, i need to increment two times and there's no other better way to do this? – Crazy Nov 24 '17 at 17:05
  • That's exactly what I mean – Mark Baker Nov 24 '17 at 17:05
  • `$alphabet = chr(ord($alphabet)+2);` – splash58 Nov 24 '17 at 17:06
  • @splash - works until $alphabet is `Y` or `Z`, then it gets rather different to the functionality that `++` would give – Mark Baker Nov 24 '17 at 17:07
  • @MarkBaker, I hope, OP will not go so far :) – splash58 Nov 24 '17 at 17:11
  • @splash58 If it's wanted for Excel spreadsheets, then it could go as high as IV or even XFD for the latest versions of MS Excel – Mark Baker Nov 24 '17 at 17:40
  • @Mark XFD? What version is that? How many lines can it handle? Every single day I have to stitch together spreadsheets because I go above one million lines. – Andreas Nov 24 '17 at 18:07
  • @Andreas That is a column limit (16,384 columns), 1,048,576 rows is the row limit for Excel2007 and above – Mark Baker Nov 24 '17 at 18:58
  • @Mark ok. I thought it was something new. It would be great if they make it possible to swap columns for lines. I usually only need 200-300.000 more lines. – Andreas Nov 24 '17 at 19:10
  • Perhaps relevant to researchers: https://stackoverflow.com/q/46095569/2943403 – mickmackusa Apr 30 '18 at 07:45

2 Answers2

2

You can have an array with the alphabet created by range.
The just echo the one you need with a counter.

$alphabet = range("A", "Z");
$i =0;

Echo $alphabet[$i];
$i =($i+25)%26;
Echo $alphabet[$i];

https://3v4l.org/U49OY

Edit Mark has a good point in comments above.
Added a mod calculation to keep it between A-Z.

In the code it's the ($i+25)%26; that is the increment value.

Andreas
  • 23,610
  • 6
  • 30
  • 62
1

Use php chr and php ord

$alphabet = "A";
$ascii = ord($alphabet);
$ascii += 2;
echo $alphabet = chr($ascii);

LIve demo : https://eval.in/907132

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109