Function that returns next character in PHP ASCII table

Asked

Viewed 323 times

0

I would like to make a function in PHP that would receive a character and return the next character, according to the ASCII table.

For example: receives 'a' and returns 'b'. I know how to do this in C, which would be

char funcao(char C) {
  return C++;
}

But this way it doesn’t work in PHP. Someone knows how to do it?

  • And if the input letter is z, the exit must be }?

  • Yes, according to the ASCII table.

2 answers

1


Just convert the value to integer with the function ord(), increment the desired value and convert to string again with the function chr().

function charOffset(string $char, int $offset = 3): string
{
    return chr(ord($char) + $offset);
}

So just call the function:

echo charOffset('a');  // 'd'
echo charOffset('f', 10);  // 'p'

See working on Repl.it | Ideone

  • It worked right here, thank you!

0

See if that’s what you want.

<?php

$a = ord("a"); #pega o dec de "a"

function transform($transform)
{
    $otro = $transform + 3; #adiciona +3 ao inteiro de $transform
    var_dump(chr($otro));   #mostra na tela o dec de 100 "d"
}

transform($a);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.