2

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'

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200

3 Answers3

11

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!

Community
  • 1
  • 1
Alessi 42
  • 1,112
  • 11
  • 26
2

i think you can increment value like this.

 $a = a;
  for ($n = 0; $n <= 10; $n++) {
    echo '<p>'.$a.'</p>';
    $a++;
  }

It outputs this

a

b

c

d

e

f

g

h

i

j

k
Maitray Suthar
  • 263
  • 2
  • 13
0

I don't think php can do that, that way. You could do this:

$num = 10;
for($i=0;$i<$num;$i++){
  ++$a;
}
admcfajn
  • 2,013
  • 3
  • 24
  • 32