Crazy
Crazy

Reputation: 867

How to increment the letter of alphabet by 2 or more instead of 1 each time?

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.

Upvotes: 1

Views: 958

Answers (2)

Andreas
Andreas

Reputation: 23958

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.

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

Use php chr and php ord

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

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

Upvotes: 1

Related Questions