Introduction
In this article I will explain converting between ASCII characters and codes in PHP. I want to retrieve the ASCII code corresponding to a specified character. So I will use the two important functions "chr()" and "ord()" for retrieving the ASCII code. First of all I will discuss the chr() function in PHP.
Syntax
Parameter |
Description |
ASCII |
Required an ASCII value. |
This function returns the specified character.
Example
The chr() function returns the character for the specified ASCII value and this function is the complement of ord().
<?php
$str = "The string ends in escape: ";
$str .= chr(27);
//Often this is more useful
$str = sprintf("The string ends in escape: %c", 27);
echo $str;
?>
The printf() function returns a formatted string with a format string of "%c".
Output
Example
<?php
// define ASCII code
$str1 = 65;
$str2 = 66;
$str3 = 67;
$str4 = 68;
$str5 = 69;
$str6 = 60;
$str7 = 61;
$str8 = 62;
$str9 = 63;
// retrieve character
$char1 = chr($str1);
$char2 = chr($str2);
$char3 = chr($str3);
$char4 = chr($str4);
$char5 = chr($str5);
$char6 = chr($str6);
$char7 = chr($str7);
$char8 = chr($str8);
$char9 = chr($str9);
echo $char1."<br>";
echo $char2."<br>";
echo $char3."<br>";
echo $char4."<br>";
echo $char5."<br>";
echo $char6."<br>";
echo $char7."<br>";
echo $char8."<br>";
echo $char9."<br>";
?>
Output
Next, I will discuss the ord() function in PHP. The ord() function converts an ASCII code to a character. The chr() function returns the ASCII value of the first character of the string.
Syntax
Parameter |
Description |
string |
Required the string to get an ASCII code value. |
Returns the ASCII value as an integer.
Example
<?php
// define character
$char1 = "\r";
$char2 = "\t";
$char3 = "\n";
$char4 = "A";
$char5 = "a";
$char6 = "Z";
$char7 = "z";
// retrieve ASCII code
$asc1 = ord($char1);
$asc2 = ord($char2);
$asc3 = ord($char3);
$asc4 = ord($char4);
$asc5 = ord($char5);
$asc6 = ord($char6);
$asc7 = ord($char7);
echo 'ASCII value of \r is ' . $asc1."<br>";
echo 'ASCII value of \t is ' . $asc2."<br>";
echo 'ASCII value of \n is ' . $asc3."<br>";
echo "ASCII value of A is $asc4"."<br>";
echo "ASCII value of a is $asc5"."<br>";
echo "ASCII value of Z is $asc6"."<br>";
echo "ASCII value of z is $asc7"."<br>";
?>
Output