5

Can someone suggest a (preferably) graceful way to convert an ASCII character to its decimal equivalent using PHP?

5 Answers 5

12
function ascii_to_dec($str)
{
  for ($i = 0, $j = strlen($str); $i < $j; $i++) {
    $dec_array[] = ord($str{$i});
  }
  return $dec_array;
}

example usage :

$ascii ="\t";
print_r( ascii_to_dec($ascii));

returns an array

Array
(
    [0] => 9
)
Sign up to request clarification or add additional context in comments.

1 Comment

Inverse function: foreach ($dec_array as $dec_code) { $str .= chr($dec_code); }
5

ord() is what you need

Comments

3

ord() returns the integer ascii value of a character

chr() returns a character from an ascii value

Comments

1

Try ord.

Comments

0

Just to add onto streetparade's answer

foreach ($array as $decval)
{
  echo $decval;
}

returns raw dec for the characters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.